user2430797 user2430797 - 4 years ago 112
C# Question

How to select programatically an item in the combo box when using key,value pair

Could someone please explain how I could select programatically an item in the ComboBox when the item is defined like this:

class ComboboxItem
{
public string DisplayString;
public string Key;

public ComboboxItem(string key, string displayString)
{
Key = key;
DisplayString = displayString;
}

// Generates the text shown in the combo box
public override string ToString()
{
return DisplayString;
}
}


The combo box gets populated with items at runtime like this:

myCombo.Items.Add(new ComboboxItem(“<key>“, “<text_to_display>”));


I need to select an item programatically based on the key but I cannot use the suggestion made here: Set the selecteditem of a combobox based on key,value pair. because I don't have foreknowledge of the data items as the ComboBox gets populated at runtime. Could someone please help? Many thanks.

EDIT - this is a winforms app.

Answer Source

Try something like this

comboBox1.Items.Add(new ComboboxItem("a", "a"));
            comboBox1.Items.Add(new ComboboxItem("b", "b"));
            comboBox1.Items.Add(new ComboboxItem("c", "c"));
            comboBox1.Items.Add(new ComboboxItem("d", "d"));

            var key = "c";

            foreach (var item in comboBox1.Items)
            {
                var comboItem = (ComboboxItem) item;
                if (comboItem.Key.Equals(key))
                    comboBox1.SelectedItem = comboItem;
            }

I have just made a Winforms project and it worked. The combobox showed the "c" as selected value

You could use linq also. This could be a method to select your item

public void SelectItem(string key)
        {
            var comboItem = comboBox1.Items
                .Cast<ComboboxItem>()
                .FirstOrDefault(item => item.Key.Equals(key));
            if (comboItem == null)
            {
                //do whatever you want
            }
            else
            {
                comboBox1.SelectedItem = comboItem;
            }
        }

Hope it helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download