Add Key Value Pairs to a Combobox using WPF and C#

It’s pretty easy to populate and read from a ComboBox when the selected item is the same as the selected value. I.e. just simply use:

string selection = comboBox1.SelectedValue.ToString();

However, when you need the value to be different from the item (I.e. display value). Perhaps you want to display the Month Names but use the Month Number within your logic. In this case you would want to store the following Key, Value pairs ("January, 1", "February, 2", "March, 3", "April, 4", etc…). I looked for a simple and straight forward way to do this but working through it could only do it after some effort.

What I ended up having to do was to create a class to store my Key-Value / Item-Value pairs. Below is the class:

public class ComboBoxPairs
{
    public string monthName { get; set; }
    public int monthNumber { get; set; }
 
    public ComboBoxPairs(string MonthName,
                         int MonthNumber )
    {
        monthName = MonthName ;
        monthNumber = MonthNumber ;
    }
}

I then load the months into a List of ComboBoxPairs class and bind it to the comboBox, like this:

List<ComboBoxPairs> cbp = new List<ComboBoxPairs>();
 
cbp.Add(new ComboBoxPairs("January", 1));
cbp.Add(new ComboBoxPairs("February", 2));
cbp.Add(new ComboBoxPairs("March", 3));
.......
 
comboBox1.DisplayMemberPath = "monthName";
comboBox1.SelectedValuePath = "monthNumber";
comboBox1.ItemsSource = cbp;            
comboBox1.Text = "January";

It is important that the DisplayMemberPath name and the SelectedValuePath match the property names within the class you create. Meaning the names they are given within the combobox need to be the same as the name the pair has in the class. (monthName and monthNumber)

Once you have this, then accessing both the key and the value is pretty straight forward.

ComboBoxPairs cbp = (ComboBoxPairs)comboBox1.SelectedItem;
string monthName = cbp.monthName;
int monthNumber = cbp.monthNumber;

You need to force the conversion of the current SelectedItem to an instance of the ComboBoxPairs class. This is generally refered to as "boxing/unboxing". Then use that instance to get the values of each.

I was a little surprised that I couldn’t simply access both the Key and the Value directly, however, I am not sure how often someone would need to get both the key and value at one go. However, I did need it so I am certain there is at least one other person who also may need it. Therefore I wrote this article.

Download the source




Leave a Comment

Your email address will not be published.