如何在c#中插入一个datagridview值到数据库的按钮点击
本文关键字:datagridview 数据库 按钮 一个 插入 | 更新日期: 2023-09-27 18:01:29
我有两个控件在我的winform,即文本框和datagridview .textboxes数据输入由用户保存在一个表(购买)和datagridview数据输入保存在另一个表(purchasedetail)。我的问题是文本框值保存在购买表中,但datagridview值没有保存到数据库。
here is my save button code:
private void SAVE(object sender, EventArgs e)
{
try
{
con.Open();
cmd = new SqlCommand("insert into Purchase(purchase_id,purchase_date,ref_no,total,total_wrds) values(@purchase_id,@purchase_date,@ref_no,@total,@total_wrds)", con);
cmd.Parameters.AddWithValue("@purchase_id", textid.Text);
cmd.Parameters.AddWithValue("@purchase_date", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("@ref_no", textrno.Text);
cmd.Parameters.AddWithValue("@total", texttotal.Text);
cmd.Parameters.AddWithValue("@total_wrds", textinwrds.Text);
cmd.ExecuteNonQuery();
foreach (DataGridViewRow row in datagrid.Rows)
{
if (!row.IsNewRow)
{
using(SqlCommand cmd11 = new SqlCommand("insert into Purchasedetail(product_id, product_name,qty,price,tax,discount,total)values(@product_id, @product_name,@qty,@price,@tax,@discount,@total)", con))
{
cmd11.Parameters.AddWithValue("@product_id", row.Cells[0].Value);
cmd11.Parameters.AddWithValue("@product_name", row.Cells[1].Value);
cmd11.Parameters.AddWithValue("@qty", row.Cells[2].Value);
cmd11.Parameters.AddWithValue("@price", row.Cells[3].Value);
cmd11.Parameters.AddWithValue("@tax", row.Cells[4].Value);
cmd11.Parameters.AddWithValue("@discount", row.Cells[5].Value);
cmd11.Parameters.AddWithValue("@total", row.Cells[6].Value);
cmd11.ExecuteNonQuery();
datagrid.Refresh();
//row.ReadOnly = true;
//clm.ReadOnly = true;
MessageBox.Show("Added Sucessfully", "OUTPUT", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
我假设您想将DataGrid表保存到数据库中的一个表中。有了这个答案,我建议您在数据网格中处理数据,而不是在文本框中,如果不是非常必要的话。首先,我解释一下代码。由于您的临时DG表将被"添加",因此您需要首先清除它。然后将itemssource转换为表格,就可以保存了。使用适配器更新表。
try
{
SqlCommand ClearTableCommand = new SqlCommand("delete from " + CurrentTableName + ";", myconnection);
ClearTableCommand.ExecuteNonQuery();
DataTable myDT;
DataView myview;
myview = (DataView)dataGrid1.ItemsSource;
myDT = myview.ToTable(CurrentTableName);
using (SqlDataAdapter Adapter1 = new SqlDataAdapter("select * from " + CurrentTableName + "", myconnection))
{
Adapter1.UpdateCommand = new SqlCommandBuilder(Adapter1).GetUpdateCommand(true);
Adapter1.AcceptChangesDuringFill = false;
Adapter1.AcceptChangesDuringUpdate = true;
Adapter1.Update(myDT);
}
}
catch (Exception ex)
{
System.windows.MessageBox.Show(ex.Message);
}