tags:

views:

123

answers:

4

How can I select the item in the comboBox with key "02"?

public class GenericComboBox
{
    private string _key = string.Empty;
    private string _value = string.Empty;

    public string Key
    {
        get { return _key; }
        set { _key = value; }
    }

    public string Value
    {
        get { return _value; }
        set { _value = value; }
    }

    public GenericComboBox(string key, string value)
    {
        _key = key;
        _value = value;
    }
}

//Add data
IList<GenericComboBox> data = new List<GenericComboBox>();

data.Add(new GenericComboBox("01", "01 text"));
data.Add(new GenericComboBox("02", "02 text"));
data.Add(new GenericComboBox("03", "03 text"));

comboBox1.DataSource = data;
comboBox1.ValueMember = "Value";

//comboBox1.SelectItem With key equal "02"

Thank you.

+1  A: 

Set the SelectedValue property. The ComboBox will select the item with that value set on it.

Jon Seigel
A: 

.Net 2.0: (data needs to be a List not an IList for this one.)

    this.comboBox1.SelectedItem = data.Find(delegate(GenericComboBox gc) {return gc.Key == "02"; });

.Net 3.5:

    this.comboBox1.SelectedItem = data.First(gc => gc.Key == "02");
BFree
How can I do in case of not having access to variable data?. For example if I select the comboBox in a button click event
andres descalzo
comboBox1.SelectedItem = ((List<GenericComboBox>)comboBox1.DataSource).Find(delegate(GenericComboBox gc) { return gc.Key == "02"; });
andres descalzo
A: 

How about using Dictionary instead of an IList? Then you can retrieve the value using the key.

Vijay Patel
+1  A: 

Override Equals in your GenericComboBox class:

public override bool Equals(object obj)
{
   return string.Compare(Key, obj.ToString(), true) == 0;
}

Then this code should work:

comboBox1.SelectedItem = "02";
Austin Salonen