combox的键值对应用: KeyValuePair<TKey, TValue>
combox的item列表里存在字符,如何将多个字符与序号0123。。。对应?
键值对 KeyValuePair<TKey, TValue> 就很好地帮我们解决了问题。
举个栗子:
private void Form1_Load(object sender, EventArgs e) { setComboxItemData(comboBox1,new int[]{0,1,2,3,4,5}); } private void setComboxItemData(ComboBox cb, int[] data) { cb.DisplayMember="key"; cb.ValueMember = "value"; System.Diagnostics.Debug.Assert(cb.Items.Count==data.Length); List<KeyValuePair<string, int>> listItem= new List<KeyValuePair<string, int>>();; for (int i = 0; i < cb.Items.Count; i++) {
//KeyValuePair<string, int> Item = new KeyValuePair<string,int>(cb.Items[i].ToString(),data[i]);
//cb.Items[i] = Item;
listItem.Add(new KeyValuePair<string,int>(cb.Items[i].ToString(), data[i]));
} cb.DataSource = listItem; System.Diagnostics.Debug.Assert(cb.DataSource != null); } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { KeyValuePair<string,int> key=(KeyValuePair<string,int>)(comboBox1.SelectedItem); int index = key.Value; string name = key.Key; }
这样:在comboBox1的selected事件中 通过读取选择的item 就可知道选择了第几项