场景描述
在使用 C# 开发的某个界面中,左侧的 DataGridView
绑定了一个 DataTable
的部分字段,右侧的 TextBox
也绑定了同一个 DataTable
的部分字段。这样,一个 DataTable
的行数据被分布绑定在左侧和右侧。
当在右侧的 TextBox
中随意修改某个字段的值后,直接调用 dt.GetChanges()
方法,却发现返回的结果为 null
,即修改未被检测到。
问题原因
经过多次调试发现,问题并不是一直存在,而是具有以下特征:
- 有时可以获取到修改的数据,调用
GetChanges()
返回正确结果。 - 有时无法获取修改的数据,调用
GetChanges()
返回null
。
这是因为当 DataTable
绑定的一行数据处于编辑状态时,编辑还未结束,DataTable
并未记录修改。
只有当焦点移开编辑控件(如 TextBox
),该行的编辑状态才会自动结束,修改才会被记录到 DataTable
中。否则,需手动调用接口结束编辑。
解决方案
为了确保在调用 GetChanges()
时,DataTable
中的编辑状态已经结束,建议通过以下方法解决。
绑定控件数据的代码实现
private BindingSource bindingSource = new BindingSource();
private void BindControls()
{
// 将 DataTable 绑定到 BindingSource
bindingSource.DataSource = dt;
dataGridView5.DataSource = bindingSource;
// 绑定 TextBox
textBox1.DataBindings.Clear();
textBox2.DataBindings.Clear();
textBox3.DataBindings.Clear();
textBox1.DataBindings.Add("Text", bindingSource, "str1");
textBox2.DataBindings.Add("Text", bindingSource, "str2");
textBox3.DataBindings.Add("Text", bindingSource, "str3");
}
调用GetChanges
前结束编辑
// 在调用 GetChanges() 之前,显式结束绑定控件的编辑状态
bindingSource.EndEdit();
DataTable dtChanges = dt.GetChanges();