2011-12-02 61 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()