我正在用 C# 编写一个 Winforms 应用程序,使用户能够使用数据 GridView 编辑和更新数据库。
问题是,我无法让它工作。我唯一设法实现的是更新 datagridview 显示的内容,但是当我进入数据库表时,数据没有变化。 我搜索了很多讨论该问题的网站,但对我来说还没有任何效果。
到目前为止我尝试过的事情:
- 将数据库绑定(bind)到datagridview
- 将
Copy to Output Directory
属性更改为Copy if newer
- 使用
dataAdapter.Update((DataTable)bindingSource1.DataSource)
执行或不执行任何更新查询。 - 在没有
dataAdapter.update(...)
的情况下执行更新查询。
这是我的代码:
public Form1()
{
InitializeComponent();
GetData("SELECT * FROM Table1");
}
void GetData(string selectCommand)
{
SqlConnection conn = new SqlConnection(Properties.Settings.Default.NewDBTESTConnectionString);
dataAdapter = new SqlDataAdapter(selectCommand, conn);
commandBuilder = new SqlCommandBuilder(dataAdapter);
table = new DataTable();
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.DataSource = bindingSource1;
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
dataAdapter.Update((DataTable)bindingSource1.DataSource);
}
最佳答案
如果不调用 bindingSource1.EndEdit
,您的底层 DataTable 看不到任何变化,因此 Update 命令没有任何要更新的内容。
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
bindingSource1.EndEdit();
DataTable dt = (DataTable)bindingSource1.DataSource;
// Just for test.... Try this with or without the EndEdit....
DataTable changedTable = dt.GetChanges();
Console.WriteLine(changedTable.Rows.Count);
int rowsUpdated = da.Update(dt);
Console.WriteLine(rowsUpdated);
}
关于c# - 如何使用Datagridview绑定(bind)源C#更新SQL Server数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26946397/