[ACCEPTED]-How to create a Winforms Combobox with Label and Value?-combobox

Accepted answer
Score: 53

I can think of a few ways:

  • override the ToString() of a City class to return Name + " / " + Id;
  • ditto, but with a TypeConverter
  • add a DisplayText property that return the same, and use DisplayMember
  • build a shim class for the data

For the last:

var data = cities.Select(city => new {
     Id = city.Id, Text = city.Name + " / " + city.Id }).ToList();
cbo.ValueMember = "Id";
cbo.DisplayMember = "Text";
cbo.DataSource = data;


Score: 41

Assuming that your values are unique, you 5 can first populate a dictionary then bind 4 the combobox to the dictionary. Unfortunately 3 databinding requires an IList or an IListSource 2 so you have to wrap it in Binding Source. I 1 found the solution here.

    private void PopulateComboBox()
        var dict = new Dictionary<int, string>();
        dict.Add(2324, "Toronto");
        dict.Add(64547, "Vancouver");
        dict.Add(42329, "Foobar");

        comboBox1.DataSource = new BindingSource(dict, null);
        comboBox1.DisplayMember = "Value";
        comboBox1.ValueMember = "Key";
Score: 7

You could try creating a small class called 2 ComboBoxItem, like so:

public class ComboBoxItem<T>
    public string Label { get; set; }
    public T Value { get; set; }

    public override string ToString()
        return Label ?? string.Empty;

And then when you need to get 1 an object, just cast it to a ComboBoxItem.

Score: 5

A ComboBox can be bound to a collection 16 of objects by setting its DataSource property.

By default, the 15 SelectedValue property will be give the 14 object that was selected, and the list will 13 call ToString on each object and display the result.
However, if 12 you set the DisplayMember property of the ComboBox, it 11 will display the value of the property 10 named in DisplayMember in the list. Similarly, you 9 can set the ValueMember property of the ComboBox and 8 the SelectedValue proeprty will return the 7 value of the property named by ValueMember.

Therefore, you 6 need to bind the ComboBox to a list of objects 5 that have Name and Value properties.
You can then 4 set the ComboBox's [DisplayMember property to Name and ValueMember property 3 to Value.

EDIT: You can also call the Add method and 2 give it such an object instead of databinding. Alternatively, you 1 could bind it to a List<T> or an array.

Score: 2

There is a property called DisplayMember = name of property 3 whose value will be used for display, and 2 ValueMember which is the property of the to use for 1 the value.

Score: 1
        anestezi.DisplayMember = "Text";
        anestezi.ValueMember = "Value";
        anestezi.DataSource = new[] { 
            new { Text = "Genel", Value = "G" }, 
            new { Text = "Lokal", Value = "L" },
            new { Text = "Sedasyon", Value = "S" }
        anestezi.SelectedIndex = 0;


More Related questions