WinForms ComboBox data binding gotcha

Think you are doing something like the adhering to

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 currently we have 2 combination boxes bound to that array, and also every little thing functions penalty. Yet when you transform the value of one combination box, it transforms BOTH combination boxes to the one you simply picked.

Currently, I recognize that Arrays are constantly gone by reference (found out that when i found out C :D), yet why in the world would certainly the combination boxes transform with each other? I do not think the combination box control is changing the collection in all.

As a workaround, do not this would certainly attain the capability that is expected/desired

ComboBox box = new ComboBox();
box.DataSource = myitems.ToArray();
2019-05-03 17:39:03
Source Share
Answers: 1

This concerns just how information bindings are set up in the dotnet structure, specifically the BindingContext On a high degree it suggests that if you have not defined or else each kind and also all the controls of the kind share the very same BindingContext. When you are establishing the DataSource building the ComboBox will certainly make use of the BindingContext to get a ConcurrenyMangager that covers the checklist. The ConcurrenyManager tracks such points as the existing picked placement in the checklist.

When you set the DataSource of the 2nd ComboBox it will certainly make use of the very same BindingContext (the kinds) which will certainly produce a reference to the very same ConcurrencyManager as above made use of to set up the information bindings.

To get an extra thorough description see BindingContext.

2019-05-09 08:27:34

Related questions