DooDoo
DooDoo

Reputation: 13487

Binding a DataTable (or List) to two Combo Boxes

I have a DataTable (or Generic List) that I want to bind to 2 ComboBox. If I bind it when one ComboBox changes, the other ComboBox changes too to the first ComboBox value.

How can I separate them?

I've created another DataTable and assigned the main DataTable to it but the problem still remains.

Upvotes: 0

Views: 1915

Answers (3)

Nighil
Nighil

Reputation: 4127

Since you are refering same object to both combobox when one changes other also changes

DataTable dt;
combobox1.DataSource=dt;
DataTable dt2;
dt2 =  dt.Copy();
combobox2.DataSource=dt2;

Upvotes: 1

Tridus
Tridus

Reputation: 5081

The problem is that just creating a new DataTable (or List) variable and assigning the existing list to it doesn't create a new one. It just creates another reference that points to the same one. So you have don't have two of the same thing, you have one thing that you can get to in two different ways. It's a subtle difficulty that often trips people up. :)

The Clone() method that NDC mentioned is one answer. For Lists you can also use ToArray() to make an array and bind that (as the Array won't have the same problems).

Upvotes: 0

Eilistraee
Eilistraee

Reputation: 8290

It looks like you bound the SelectedItem properties of your two Comboboxes to the same property. If you want to select different items according to your comboboxes, you should use different properties:

<ComboBox ItemSource="{Binding List}" SeletectedItem="{Binding SelectedItem1, Mode=TwoWay}"/>
<ComboBox ItemSource="{Binding List}" SeletectedItem="{Binding SelectedItem2, Mode=TwoWay}"/>

Upvotes: 0

Related Questions