Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 883
Мitke Avatar asked Jan 04 '12 00:01

Мitke


3 Answers

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, "");
like image 150
Abbas Avatar answered Nov 05 '22 15:11

Abbas


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;
like image 44
competent_tech Avatar answered Nov 05 '22 13:11

competent_tech


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.

like image 3
John Avatar answered Nov 05 '22 15:11

John