2011-12-02 63 views
0

我有填充像这样的组合框:根据键值对设置组合框的selecteditem。

this.reqTypeInput.Items.Add(new RequestType("Label 1", "Value1")); 
this.reqTypeInput.Items.Add(new RequestType("Label 2", "value2")); 
this.reqTypeInput.Items.Add(new RequestType("Label 3", "value3")); 

我的RequestType类是:

class RequestType 
{ 
    public string Text { get; set; } 
    public string Value { get; set; } 

    public RequestType(string text, string val) 
    { 
     Text = text; 
     Value = val; 
    } 

    public override string ToString() 
    { 
     return Text; 
    } 
} 

我的值。例如, “值1”。如何将组合框的selectedItem设置为对象{Label 1,Value1}?

我曾尝试:

this.reqTypeInput.SelectedIndex = this.reqTypeInput.Items.IndexOf("Value1"); 

回答

3

如果请求类型不改变,你可以先存储在变量中的每个请求类型的对象,然后ComboBox的SelectedItem属性设置为变量。

例如:

RequestType type1 = New RequestType("Label 1", "Value 1"); 
RequestType type2 = New RequestType("Label 2", "Value 2"); 

reqTypeInput.Items.Add(type1); 
reqTypeInput.Items.Add(type2); 

然后,设置这样的:

reqTypeInput.SelectedItem = type2; 
5

看起来你正在努力寻找索引,仿佛你ComboBox只包含字符串值,当它实际上包含RequestType对象。您是否尝试覆盖您的Equals运营商?

检出this SO postthis one为覆盖Equals的示例。

编辑:作为另一个答复中提到,一个好的做法是填充您在ComboBox希望对象的集合,然后该集合绑定到你的ComboBox。我在这里回答的第一个链接就是一个例子。

1

你可以试试这个:

RequestType type1 = New RequestType("Label 1", "Value 1"); 
RequestType type2 = New RequestType("Label 2", "Value 2"); 

reqTypeInput.Items.Add(type1); 
reqTypeInput.Items.Add(type2); 

this.reqTypeInput.SelectedIndex = this.reqTypeInput.Items.IndexOf(type1); 

HTH。

0

Lot的选择,List,SortedList,Dictionary,SortedDictionary。 但是,基本上你可以将你的RequestTypes集合保存在一个列表中,然后用它填充组合,如果你愿意,你甚至可以绑定。

有关您的请求类型集合的组合knopws唯一的事情就是每个RequestType的ToString方法的结果。如果你想通过Value来查找,那么Combox只会看到你输入的内容,它是RequestType.ToString()