Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Bind A Dictionary To A ComboBox In WinForms?

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.

like image 529
TLJ Avatar asked Oct 23 '25 13:10

TLJ


1 Answers

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);
    }

enter image description here

like image 74
jsanalytics Avatar answered Oct 25 '25 03:10

jsanalytics