2009-10-13 58 views
1

如何使用键“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" 

谢谢。

回答

1

NET 2.0:(数据需要一个List不是一个IList此一个。)

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

的.Net 3.5:

this.comboBox1.SelectedItem = data.First(gc => gc.Key == "02"); 
+0

我怎样才能在不通往可变数据的情况下怎么办?例如,如果我在按钮单击事件中选择了组合框 – 2009-10-13 14:21:45

+0

comboBox1.SelectedItem =((List )comboBox1.DataSource).Find(delegate(GenericComboBox gc){return gc.Key ==“02”;}) ; – 2009-10-13 14:23:34

1

设置SelectedValue属性。 ComboBox将选择设置了该值的项目。

0

如何使用字典,而不是一个IList的?然后您可以使用该键检索值。

1

覆盖Equals在GenericComboBox类:

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

那么这个代码应工作:

comboBox1.SelectedItem = "02";