[英]C# - Update databound combo box automatically
So I've found a lot of questions similar to this tho nothing really solve my problem..所以我发现了很多与此类似的问题,但没有什么能真正解决我的问题..
I have a combobx that is bounded by a datasource我有一个受数据源限制的组合框
cmbProduct.DataSource = this.masterDataSet.Product.Where(x => x.Location == getLocation).AsDataView();
cmbProduct.DisplayMember = "Product";
cmbProduct.ValueMember = "Product";
But whenever i update the source, the combobox items does not update automatically.但是每当我更新源时,组合框项目都不会自动更新。 I still need to close then reopen the form.
我仍然需要关闭然后重新打开表单。
is there a method to refresh/reload/or update the combobox?有没有刷新/重新加载/或更新组合框的方法?
You could implement an event that fires whenever the DataSet changes.您可以实现一个在 DataSet 更改时触发的事件。 The event could reset the Datasource and rebind it.
该事件可以重置数据源并重新绑定它。
Somewhere in your code:在您的代码中的某处:
yourDataController.DataChanged += OnDataChanged;
and the implementation和实施
public void OnDataChanged(object sender, EventArgs e)
{
cmbProduct.Items.Clear();
cmbProduct.DataSource = this.masterDataSet.Product.Where(x => x.Location == getLocation).AsDataView();
cmbProduct.DisplayMember = "Product";
cmbProduct.ValueMember = "Product";
}
Edit: Of course you need to manually implement the event and cause it to fire every time your data changes.编辑:当然,您需要手动实现事件并在每次数据更改时触发它。
Solution 1解决方案1
You can use an implementation of IBindingList
as DataSource
to view changes of data source in the bound list control (complex two-way data binding).您可以使用
IBindingList
作为DataSource
的实现来查看绑定列表控件中数据源的更改(复杂的双向数据绑定)。 The most suitable implementation is System.ComponentModel.BindingList<T>
.最合适的实现是
System.ComponentModel.BindingList<T>
。
Then when you add items to the binding list, or remove item from it you will see changes immediately in the control.然后,当您将项目添加到绑定列表或从中删除项目时,您将立即在控件中看到更改。
Solution 2解决方案2
But as a more simple solution with less changes for you, you can reset the databinding of your cmbProduct
this way when you need;但是作为一个更简单的解决方案,您可以在需要时
cmbProduct
这种方式重置cmbProduct
的数据绑定; for example after a change, call RefreshBindings();
例如在更改后,调用
RefreshBindings();
: :
public void RefreshBindings()
{
var list = put your updated list here;
this.cmbProduct.DataSource = null;
this.cmbProduct.DataSource = list;
this.cmbProduct.DisplayMember = "set the display member here";
this.cmbProduct.ValueMember = "set the value member here";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.