我正在用 C# 编写一个 Winforms 应用程序,使用户能够使用 datagridview 编辑和更新数据库。
问题是,我无法让它发挥作用。我唯一能做到的就是更新 datagridview 显示的内容,但是当我进入数据库表时,数据没有变化。
我搜索了很多讨论这个问题的网站,但没有任何对我有用。
到目前为止我尝试过的事情:
- 将数据库绑定到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
您的基础数据表没有看到任何更改,因此更新命令没有任何可更新的内容。
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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)