Update ComboBox Items Runtime in Winforms C#

Update ComboBox Items Runtime in Winforms C#

Added by Mind Hunter updated on Thursday, December 7, 2017

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.

add_item_binding_source

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

bind_dic_array_combobox

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

bind_key_value_combobox

About

29 Tutorials
25 Snippets
6 Products

More

Contact Us

Contact us

Stay Connected