2011-12-01 69 views
1

我有comboBox組件,我添加的項目如comboBox1.Items.Add("Item1")。但我也需要知道關於這個項目的其他信息。所以如果我點擊「Item1」,我需要獲得"102454"。 可以以某種方式將102454保存到組合框上的「Item1」。C#組合框在web應用程序中的下拉列表

在網絡aplication有下拉列表看起來像

<select> 
    <option value="102454">Item1</option> 
</select> 

,當我點擊「項目1」我得到102454

我可以在Windows桌面應用程序中使用組合框嗎?

回答

3

編輯更好的解決方案:

使用KeyValuePairValueMember \ DisplayValue

comboBox1.ValueMember = "Key"; 
comboBox1.DisplayMember = "Value"; 

comboBox1.Items.Add(new KeyValuePair<int, string>(102454, "Item1")); 

正如克里斯蒂安指出,這可以擴展到更加靈活 - 你可以把你喜歡的任何對象到項目列表中,並將組合框中的值和顯示成員設置爲所需的任何屬性路徑。


拿到鑰匙回來以後,你可以這樣做:

var item = combobox1.SelectedItem; 

int key = ((KeyValuePair<int, string>)item).Key; 
+1

這是最靈活的解決方案。因爲「KeyValuePair」可以用任何對象來改變。如果你使用例如「Person」作爲對象,您可以設置: comboBox1.ValueMember =「SSN」; comboBox1.DisplayMember =「Name」; – ravndal

+0

thx會嘗試。但正確的代碼是KeyValuePair (102454,「Item1」) – senzacionale

+0

嗯我怎麼現在可以得到鑰匙回來。我無法讀取102454或可以嗎? – senzacionale

0

A創建了一個像Mark Pim建議的類似的類;然而,我的使用泛型。 我當然不會選擇使Value屬性成爲字符串類型。

public class ListItem<TKey> : IComparable<ListItem<TKey>> 
    { 
     /// <summary> 
     /// Gets or sets the data that is associated with this ListItem instance. 
     /// </summary> 
     public TKey Key 
     { 
      get; 
      set; 
     } 

     /// <summary> 
     /// Gets or sets the description that must be shown for this ListItem. 
     /// </summary> 
     public string Description 
     { 
      get; 
      set; 
     } 

     /// <summary> 
     /// Initializes a new instance of the ListItem class 
     /// </summary> 
     /// <param name="key"></param> 
     /// <param name="description"></param> 
     public ListItem(TKey key, string description) 
     { 
      this.Key = key; 
      this.Description = description; 
     } 

     public int CompareTo(ListItem<TKey> other) 
     { 
      return Comparer<String>.Default.Compare (Description, other.Description); 
     } 

     public override string ToString() 
     { 
      return this.Description; 
     } 
    } 

這也很容易創建它是非一般的變體:

public class ListItem : ListItem<object> 
    { 
     /// <summary> 
     /// Initializes a new instance of the <see cref="ListItem"/> class. 
     /// </summary> 
     /// <param name="key"></param> 
     /// <param name="description"></param> 
     public ListItem(object key, string description) 
      : base (key, description) 
     { 
     } 
    } 
相關問題