Assume you are doing something like the following
List<string> myitems = new List<string>
{
"Item 1",
"Item 2",
"Item 3"
};
ComboBox box = new ComboBox();
box.DataSource = myitems;
ComboBox box2 = new ComboBox();
box2.DataSource = myitems
So now we have 2 combo boxes bound to that array, and everything works fine. But when you change the value of one combo box, it changes BOTH combo boxes to the one you just selected.
Now, I know that Arrays are always passed by reference (learned that when i learned C :D), but why on earth would the combo boxes change together? I don't believe the combo box control is modifying the collection at all.
As a workaround, don't this would achieve the functionality that is expected/desired
ComboBox box = new ComboBox();
box.DataSource = myitems.ToArray();
This has to do with how data bindings are set up in the dotnet framework, especially the
BindingContext
. On a high level it means that if you haven't specified otherwise each form and all the controls of the form share the sameBindingContext
. When you are setting theDataSource
property theComboBox
will use theBindingContext
to get aConcurrenyMangager
that wraps the list. TheConcurrenyManager
keeps track of such things as the current selected position in the list.When you set the
DataSource
of the secondComboBox
it will use the sameBindingContext
(the forms) which will yield a reference to the sameConcurrencyManager
as above used to set up the data bindings.To get a more detailed explanation see BindingContext.
A better workaround (depending on the size of the datasource) is to declare two
BindingSource
objects (new as of 2.00) bind the collection to those and then bind those to the comboboxes.I enclose a complete example.
If you want to confuse yourself even more then try always declaring bindings in the constructor. That can result in some really curious bugs, hence I always bind in the Load event.