我想在我的 Windows 窗体应用程序中创建一个类似于 html 中的下拉菜单的下拉菜单,即等。
我需要每个条目向用户显示文本,但存储要在我的应用中使用的值。
我目前正在使用组合框,但似乎无法为每个条目存储关联值。
提前致谢。
请您参考如下方法:
您可以在组合框中存储任何内容,包括包含您需要的值的对象实例以及字符串。您需要做的就是覆盖用作项目的类中的 ToString。
class Item {
public string Name = "";
public int Value = 0;
public Item(string name, int value) {
this.Name = name;
this.Value = value;
}
public override string ToString() {
return this.Name;
}
}
然后:
for (int i = 0; i < 10; i++) {
Item item = new Item("Item no. " + i.ToString(), i);
comboBox1.Items.Add(item);
}
当您使用 comboBox1.Items 时,您需要做的就是将项目转换为 Item,一切就绪。
