Problem:
From How To Bind Dictionary To ComboBox
Now we modify dictionary contents but changes are not reflected as we want.
According to MSDN documentation When the DataSource property is set, the items collection cannot be modified. Altering the dictionary object directly will not affect the ComboBox.Because the BindingSource instance used as DataSource owns a full copy of it.
Solution 1:
One possible solution is to modify directly BindingSource as.
(comboBox1.DataSource as BindingSource).Add(new KeyValuePair("key" + icount, "Value " + icount));
Here is the result.
Solution 2:
Other solution is to rebind every time dictionary contents changed.
dsdic.Add("key" + icount, "Value " + icount); comboBox1.DataSource = dsdic.ToArray();
Here is the result
Drawback of this solution is Combobox selected items reset.
Solution 3:
Another solution is to use List of KeyValuePair instead of Dictionary
List<KeyValuePair<string, string>> dslist = new List<KeyValuePair<string, string>>(); BindingSource bslist = new BindingSource(); int bcount = 1;
OnLoad add this
dslist.Add(new KeyValuePair<string, string>("k1","value1")); bslist.DataSource = dslist; comboBox1.DataSource =bslist; comboBox1.DisplayMember = "Value"; comboBox1.ValueMember = "Key";
On Button click
bcount++; dslist.Add(new KeyValuePair<string, string>("key" + bcount, "Value " + bcount)); bslist.ResetBindings(false);
and here is the result