ComboBox in Windows Form using KeyValuePairs

Published on Wednesday, January 26, 2011

The ComboBox in Windows Form is not like the same control in Web Form, it can not insert a Key and Value pair directly.

Here is a solution:

How to insert a Key and Value pair to a Windows Forms ComboBox?

1: Init and insert Key and Value pair:

  List<KeyValuePair<string, string>> data = new List<KeyValuePair<string, string>>();
 
    // Add data to the List
    data.Add(new KeyValuePair<string, string>(�Key1�, �Value1�));
    data.Add(new KeyValuePair<string, string>(�Key2�, �Value2�));
    data.Add(new KeyValuePair<string, string>(�Key3�, �Value3�));

    cbList.DataSource = null;
    cbList.Items.Clear();

    // Bind the combobox
    cbList.DataSource = new BindingSource(data, null);
    cbList.DisplayMember = �Value�;
    cbList.ValueMember = �Key�;

2: Use it:

private void cbList_SelectedIndexChanged(object sender, EventArgs e)
{
    // Get the selected item in the combobox
    KeyValuePair<string, string> selectedPair = (KeyValuePair<string, string>)cbList.SelectedItem;

    lblSelectedKey.Text = selectedPair.Key;
    lblSelectedValue.Text = selectedPair.Value;
}