c#组合框在web应用程序中的下拉列表
本文关键字:下拉列表 应用程序 web 组合 | 更新日期: 2023-09-27 18:16:24
我有comboBox组件,我正在添加项目,如comboBox1.Items.Add("Item1")
。但是我还需要知道一些关于这个项目的其他信息。所以如果我点击"Item1",我需要得到"102454"
。我可以以某种方式保存102454到"Item1"上的组合框。
在web应用程序中有一个下拉列表,看起来像
<select>
<option value="102454">Item1</option>
</select>
,当我点击"Item1",我得到102454
。
我可以在windows桌面应用程序中使用组合框吗?
编辑更好的解决方案:
Use a KeyValuePair
and ValueMember
' DisplayValue
:
comboBox1.ValueMember = "Key";
comboBox1.DisplayMember = "Value";
comboBox1.Items.Add(new KeyValuePair<int, string>(102454, "Item1"));
正如Kristian指出的那样,这可以扩展为更加灵活-您可以将任何您喜欢的对象放入项列表中,并将组合框上的值和显示成员设置为您想要的任何属性路径。
你可以这样做:
var item = combobox1.SelectedItem;
int key = ((KeyValuePair<int, string>)item).Key;
你可以看一下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)
{
}
}