combox的item列表裏存在字符,如何將多個字符與序號0123。。。對應?
鍵值對 KeyValuePair<TKey, TValue> 就很好地幫咱們解決了問題。spa
舉個栗子:code
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;orm
listItem.Add(new KeyValuePair<string,int>(cb.Items[i].ToString(), data[i]));blog
} 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 就可知道選擇了第幾項事件