I am looking for a way to bind a Dictionary to a ComboBox
such that when I update dictionary the combobox, it will reflect the change automatically back to UI.
Now I can only populate combobox but once I update the dictionary nothing reflect to combobox.
Dictionary<String,String> menuItems = new Dictionary<String,String>(){{"1","one"},{"2","two"}};
combo.DataSource = new BindingSource(menuItems, null);
combo.DisplayMember = "Value";
combo.ValueMember = "Key";
menuItems.Add("ok", "success"); // combobox doesn't get updated
==Update==
Currently I have a workaround by calling combo.DataSource = new BindingSource(menuItems, null); to refresh my UI.
Dictionary doesn't really have properties Key and Value. Use List<KeyValuePair<string,string>> instead. Also, you need to call ResetBindings() for it to work. See below:
private void Form1_Load(object sender, EventArgs e)
{
//menuItems = new Dictionary<String, String>() { { "1", "one" }, { "2", "two" } };
menuItems = new List<KeyValuePair<string,string>>() { new KeyValuePair<string, string>("1","one"), new KeyValuePair<string, string>("2","two") };
bs = new BindingSource(menuItems, null);
comboBox1.DataSource = bs;
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";
}
private void button1_Click(object sender, EventArgs e)
{
//menuItems.Add("3","three");
menuItems.Add(new KeyValuePair<string, string>("3", "three"));
bs.ResetBindings(false);
}

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With