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

So here is the way:

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: Apply:

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

Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2013 CodeEase.com Suffusion theme by Sayontan Sinha