开发者

problem with two controls having the same datasource

I am building a winforms a开发者_开发技巧pplication, i have two comboboxes which have the same datasource, the datasource is a DataTable. Now, when I select a value in one comboBox, the value of another comboBox is changed too. Is there a way make it change without affecting the other?


In that type of scenario, you can create two different binding sources, one bound to each of your combo boxes. If you set the DataSource property of each of the binding data sources to your DataTable, then your combo boxes will work independently, while still showing the same data.

The initialisation would be something like:

// Initialization of the binding sources(assuming dataTable is a populated DataTable)
bindingSource.DataSource = dataTable;
bindingSource2.DataSource = dataTable;


The WinForms binding system is detecting that both comboboxes are hooked up to the same DataSource and is (helpfully) syncing changes across the two.

To avoid this you need to ensure each combobox has a distinct DataSource.

One way is to use the appropriate non-visual component from the Toolbox (BindingSource).

Another, if you're setting up your bindings with code, is to use BindingList. Note that there is one trap with BindingList - it can act as a wrapper:

[The] BindingList constructor creates a WRAPPER collection around the original list. It doesn't create a new list containing the same elements. (I've never seen this documented, but have verified with Reflector). -- http://www.nichesoftware.co.nz/blog/200809/databinding-lists

Instead of:

editDebitAccount.DataSource = accountsList;
editCreditAccount.DataSource = accountsList;

use this:

editDebitAccount.DataSource = new BindingList(accountsList);
editCreditAccount.DataSource = new BindingList(accountsList);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜