在网页中 combox 能支持 key -> value 的方式,使用起来很方便,但今天在使用C#的时候 ComboBox 居然只能用 value 显示文本,不支持 key 了,往列表中增加大量数据的时候还了得?
没办法,只能自己动手了,研究了一下 ComboBox ,Add 增加的是 Object ,看来有戏,过程不写了,只放结果,一看就明白:
自定义 ListItem
public class ListItem { public string Key { get; set; } public string Value { get; set; } public ListItem(string pKey, string pValue) { this.Key = pKey; this.Value = pValue; } public override string ToString() { return this.Key; } }
写入数据的时候:
ListItem li = new ListItem("名称", "内容"); this.combobox1.Items.Add(li); // 在此可以增加N个 this.combobox1.Items.Add(li); this.combobox1.DisplayMember = "Key";// 对应 ListItem 的 Key this.combobox1.ValueMember = "Value";// 对应 ListItem 的 Value
读取数据的时候:
ListItem li = (ListItem)comboBox1.SelectedItem; MessageBox.Show(li.Key + li.Value);