How to make a BindingSource aware of changes in its DataSource?

我是研究僧i 提交于 2019-12-11 03:56:08

问题


I have a:

someBindingSource.DataSource = someDataSource;

And I also do:

someDataSource = foo();

foo() does new for another data source with different data.

I don't think it's correct to do the assignment every time the data source changes, i.e:

someDataSource = foo();
someBindingSource.DataSource = someDataSource;

so is there a way to make someBindingSource aware of change in someDataSource?


回答1:


If the data source implements IBindingList inteface, then the BindingSource will be informed of adding or removing items to the data source. A good implementation to use is BindingList<T>.

Also if the items of the data source implement INotifyPropertyChanged, then the BindingSource also will be notified of changes on items.

In above cases ListChanged event will be raised.

Note

  1. Pay attention, If you assign someBindingSource.DataSource = someThing; and then someThing = new SomeThing();, since someBindingSource.DataSource is pointing to previous object, there is no change and there would be no notifications.
  2. DataSourceChanged event will be raised after you assign a new value to DataSource of a BindingSource, so after someThing = new SomeThing(); in previous situation if you perform someBindingSource.DataSource = someThing; then the DataSourceChanged will be raised.


来源:https://stackoverflow.com/questions/39557420/how-to-make-a-bindingsource-aware-of-changes-in-its-datasource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!