Terry
Terry

Reputation: 41

problem with two controls having the same datasource

I am building a winforms application, 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?

Upvotes: 4

Views: 1330

Answers (2)

Bevan
Bevan

Reputation: 44307

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);

Upvotes: 1

Rhys Jones
Rhys Jones

Reputation: 3993

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;

Upvotes: 1

Related Questions