更改数据源时更新绑定控件的更好方法
问题。 我有一个数据绑定到我的表单上的属性中的字段,用于表单上的大量文本框。 我不仅更改属性中的字段值,还更改整个属性(重置为以前保存的默认值)。
我想做的是这样的事情:
((CurrencyManager)BindingContext[Row]).Refresh();
不起作用, BindingContext[Row]
是一个PropertyManager
,而不是CurrencyManager
,并且没有刷新方法。 PushData()
受保护且无法访问。 我也试过调用this.Refresh()
,并在每个控件上单独调用c.Refresh
…现在怎么办?
这是我目前使用的代码:
private void btnReset_ButtonClicked(object sender, EventArgs e) { Row = ResetRow.Clone();//use clone to break the reference, dont want to be updating the ResetRow when Row fields change. foreach (Control c in pnlBody.Controls) if (c.DataBindings.Count > 0) c.DataBindings.Clear(); DataBindandSet();//re-apply all the databindings (50) } //just a sample of the databinding function itself private void DataBindandSet() { txtAzimuth.DataBindings.Add(new NullableBinding("Text", Row, "Azimuth", true)); txtBHTemp.DataBindings.Add(new NullableBinding("Text", Row, "BHTemp", true)); //repeat 48 more times }
更新我将数据绑定设置为完整的数据绑定字符串,以查看设置null值默认值是否有任何效果,它没有。
txtAzimuth.DataBindings.Add(new NullableBinding("Text", Row, "Azimuth", true, DataSourceUpdateMode.OnPropertyChanged, ""));
Row
是表单本身的公共属性。 ResetRow
是表单上的私有属性,它被分配给Form Load上的初始行的克隆并且从未更改,它用作备份。 允许某些属性(但不是全部)的值为null,并且应显示为空字符串。 这就是NullableBinding类在幕后所做的事情
除了删除和重新应用每一个数据绑定之外,有没有人能想到更好的方法呢?
这并不是更好,使用Binding.ReadValue
可能会省去解Binding.ReadValue
和重新绑定的麻烦, 假设您绑定的对象保持不变 :
foreach (Control c in pnlBody.Controls) foreach (Binding b in c.DataBindings) b.ReadValue();
另一方面,如果您要更改底层绑定对象,则无效。 我建议在Binding
和Row
对象之间放置一个BindingSource
,这样你只需要重新绑定绑定源而不是单独重新绑定所有50个绑定。 通过调用BindingSource.CancelEdit()
或重置数据源:
RowBindingSource.DataSource = null; RowBindingSource.DataSource = this.Row;
试试这个: TableAdapter.Fill(dataTable)
我的例子: this.bankingaccountTableAdapter.Fill(this.bankDataSet.bankingaccount);