Мitke
Мitke

Reputation: 310

Strange behavior of Windows Forms combobox control

I am developing a small desktop app, and there are several drop-down lists (combobox-es) on my form. I populate a list of strings, which will be used as data source for all of them. Here is example from my Form.cs class:

List<string> datasource = new List<string>();
datasource.Add("string 1");
datasource.Add("string 2");

Then I set this list as a data source to several comboboxes:

 cmbDataType1.DataSource = datasource;
 cmbDataType2.DataSource = datasource;

This all happens in same method, which is called from the Form constructor. Here is the strange part: after I change a selected value in one of them, the same value will be set in the other one. There are no SelectedIndexChange events set. I have messed up somewhere, but I cant put my finger where...

Upvotes: 5

Views: 1977

Answers (3)

Abbas
Abbas

Reputation: 6886

The behavior that you see is by design. When you bind the same object as the data source for multiple controls, all the controls share the same binding source.

If you explicitly assign a new binding source to each control, even while using the same data source, all controls will be unbound and will act independent of each other:

cmbDataType1.DataSource = new BindingSource(datasource, "");
cmbDataType2.DataSource = new BindingSource(datasource, "");

Upvotes: 10

competent_tech
competent_tech

Reputation: 44971

You should set a new BindingContext for the control before binding the dataSource the next time:

cmbDataType1.BindingContext = new BindingContext();
cmbDataType1.DataSource = datasource;

cmbDataType2.BindingContext = new BindingContext();
cmbDataType2.DataSource = datasource;

Upvotes: 4

John
John

Reputation: 6553

Since you are binding to the same exact datasource that is the expected behavior. You will want to change your binding to be a OneWay binding or use different objects if you don't want the selecteditem to change.

Upvotes: 3

Related Questions