Binding a Windows Forms ComboBox in C#

Windows Forms

Most often when reading the selected item of a bound combobox you will need more information than just the selected text or the selected index of the combo. For example, if you have a combobox bound to a user table in your database, you will most probably want to have the full user name displayed in the combobox, but when a user is selected you will want to work with the user code or user id. In this case the combo’s selected index is of no use and neither is the display text. You need a way to be able to retrieve the user code when a user is selected.

Fortunately, this is quite easy to accomplish. All we need to do is bind our combobox to a list of KeyValuePair objects. In this article I am going to show you how to do exactly that.

To start off create a form which looks similar to the below one:

Binding a ComboBox

Now in the Form_Load event handler we must add the following code:

private void MainForm_Load(object sender, EventArgs e)
{
    // Create a List to store our KeyValuePairs
    List<KeyValuePair<string, string>> data = new List<KeyValuePair<string, string>>();

    // Add data to the List
    data.Add(new KeyValuePair<string, string>("p1", "Joe"));
    data.Add(new KeyValuePair<string, string>("p2", "David"));
    data.Add(new KeyValuePair<string, string>("p3", "Keith"));
    data.Add(new KeyValuePair<string, string>("p4", "Andrew"));
    data.Add(new KeyValuePair<string, string>("p5", "Maria"));
    
    // Clear the combobox
    cboData.DataSource = null;
    cboData.Items.Clear();

    // Bind the combobox
    cboData.DataSource = new BindingSource(data, null);
    cboData.DisplayMember = "Value";
    cboData.ValueMember = "Key";
}

In the first line of code we are creating a List object to store our KeyValuePair objects. The KeyValuePair class can be very useful since it allows you to create a pair of objects of any type, one of which is the key and the other is the value. What this means is that you can have an object of type string paired with a key of type integer for example. Or you could have a value of type MyClass with a key of type string. The combinations are limitless.

As you can see in the code, we are creating a KeyValuePair where both the key and the value are strings. We are then adding data to the List object by creating KeyValuePair instances and adding them to our List. Next we are clearing the combobox as a precaution (just in case it was populated with something already), and finally we are binding the combobox to the List.

The last two lines of the above code are critical for your binding to work correctly. We must tell the combo which is the DisplayMember and which is the ValueMember of our KeyValuePair so that it will know which object from the pair to display and which to use as the key.

Once you have created the above code run your project and you will see that the combobox is populated with the above names. The key value however cannot be seen, so let’s create some code to visually see the selected key.

Subscribe to the SelectedIndexChanged event of your combobox and add the following code:

private void cboData_SelectedIndexChanged(object sender, EventArgs e)
{
    // Get the selected item in the combobox
    KeyValuePair<string, string> selectedPair = (KeyValuePair<string, string>)cboData.SelectedItem;
    
    // Show selected information on screen
    lblSelectedKey.Text = selectedPair.Key;
    lblSelectedValue.Text = selectedPair.Value;
}

What we are doing here is retrieving the combo’s selected item and converting it to a KeyValuePair object. Then from our KeyValuePair object we are accessing the Key and the Value properties and assigning them to the labels on our form.

Now if you run the application again you should have something like the following, and as you can see the key and value are being displayed in our labels.

Binding a ComboBox

Now using this technique you can easily bind a combobox and have one value displayed while another value is used as your key.

I hope you found this useful.
Dave.

15 comments… add one
  • roblesrt Link Reply

    thanks Dave, this saves me a lot of time and is better example compared to a myriad of examples binding combobox in .net

    • Thanks for your comment. I’m glad you found the article useful.

    • Thanks for this Did such thing available in PHP also

  • thiri nwe Link Reply

    Dear sir/madam

    Thank a million. Your written codion about combo box is very useful for me .
    thans you.

  • Michael Shelnutt Link Reply

    This was perfect! – just what I was looking for – clean and simple

  • Nice!! I was looking for something like this….
    I will try!

    Thank you!

  • Hi, Nice article.. very helpful to me ….just what I needed. Thanks!

  • rashmi Link Reply

    Hello sir can u just expalin me how to do bind this from the acces database and once we select from the comboits ID should save in the database
    how to do this…………..

  • Nells Link Reply

    But James, is there a way to add keys and value form a List or database instead of manually doing it? Lets say I want to add a 1000 users, isnt there a shorte way to add them?

  • Kamrul Hasan Link Reply

    This is perfect windows form data binding in combobox . thank you @Dave for this article.

  • Fadão Link Reply

    I appreciated, now I am getting from Sql query.
    private void Get_LaundryItems()
    {
    string query = “Select * from LaundryItem”;
    SqlConnection connection = new SqlConnection(Hotel_Manager.Properties.Settings.Default.frontend_reservationConnectionString);

    SqlCommand query_table = new SqlCommand(query, connection);
    SqlDataReader reader;

    // Create a List to store our KeyValuePairs
    List<KeyValuePair> data = new List<KeyValuePair>();

    try
    {
    connection.Open();
    reader = query_table.ExecuteReader();
    while (reader.Read())
    {
    data.Add(new KeyValuePair(reader[“ItemPrice”].ToString(), reader[“ItemDesc”].ToString()));
    cbbItems.DataSource = null;
    cbbItems.Items.Clear();
    cbbItems.DataSource = new BindingSource(data, null);
    cbbItems.DisplayMember = “Value”;
    cbbItems.ValueMember = “Key”;
    }
    connection.Close();
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    }

  • Konok Das Link Reply

    Example was simply good.

  • TheDino Link Reply

    Thank you so much! After googling various answers, your’s does the trick.
    Perfect explanation.

  • Lional Link Reply

    Great script
    Helped point me in the right direction. I am very new to C# so just a quick question. I have used the combobox on a form and I want to write the key to a database.
    I have been using
    cmd.Parameters.AddWithValue(“@GrpProvince”, cboProvince.SelectedValue);
    But it just writes the word “key”

Leave a Comment