C#组合框在web应用程序中的下拉列表

问题描述:

我有comboBox组件,我添加的项目如comboBox1.Items.Add("Item1")。但我也需要知道关于这个项目的其他信息。所以如果我点击“Item1”,我需要获得"102454"。 可以以某种方式将102454保存到组合框上的“Item1”。C#组合框在web应用程序中的下拉列表

在网络aplication有下拉列表看起来像

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

,当我点击“项目1”我得到102454

我可以在Windows桌面应用程序中使用组合框吗?

编辑更好的解决方案:

使用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

你可以看看的SelectedItem财产。

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) 
     { 
     } 
    }