【发布时间】:2017-12-11 00:27:09
【问题描述】:
我有一个 DataGridView 控件和一个保存按钮。单击“保存”按钮时,我希望对 DataGridView 所做的任何更改都通过 DataAdapter Update() 命令反映在我的数据库中。但是,在点击保存按钮并重新加载表单后,更新不存在。
这是目前保存按钮的所有代码:
private void btnSave_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=addtool.database.windows.net;Initial Catalog=AddToolToInventoryDB;User id=kanerbw; Password=Rabaraba!11;");
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("select * from ToolTB", con);
SqlCommandBuilder myBuilder = new SqlCommandBuilder(adapter);
con.Open();
SqlCommandBuilder scb = new SqlCommandBuilder(adapter);
myBuilder.GetUpdateCommand();
adapter.UpdateCommand = myBuilder.GetUpdateCommand();
adapter.Update(dt);
con.Close();
}
编辑:我忘记将我的 DGV 的数据源设置为数据表。这是工作代码:
private void btnSave_Click(object sender, EventArgs e)
{
using (var con = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("select * from ToolTB", con);
SqlCommandBuilder myBuilder = new SqlCommandBuilder(adapter);
dgvProductInfo.DataSource = dt;
adapter.UpdateCommand = myBuilder.GetUpdateCommand();
adapter.Update(dt);
dt.Clear();
adapter.Fill(dt);
}
}
【问题讨论】:
标签: c# .net winforms datagridview dataadapter