實現(xiàn)功能:
datatable綁定comboBox,在下拉菜單中顯示對應數(shù)據(jù)
實現(xiàn)方法:
1,、生成datatable,,并為combox綁定數(shù)據(jù)源:
comboBox1.DataSource = dt1; comboBox1.DisplayMember = "用戶編碼"; comboBox1.ValueMember = "ID"; this.comboBox1.SelectedIndex = -1;
2、在combox的SelectedIndexChanged事件中添加如下方法:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { int iCurrentIndex = this.comboBox1.SelectedIndex; if (iCurrentIndex < 0) return;
DataRow dr = dt1.Rows[iCurrentIndex]; iID = Int32.Parse(dr["ID"].ToString());
}
另:如果textBox也想綁定該數(shù)據(jù)源,,實現(xiàn)連動(如輸入編碼顯示對應名稱)
3,、在textBox的TextChanged事件中添加如下方法:
private void textBox1_TextChanged(object sender, EventArgs e) { string strUserNo = this.textBox1.Text.Trim(); for (int i = 0; i < dt1.Rows.Count; i++) { if (dt1.Rows[i]["用戶編碼"].ToString() == strUserNo) { this.comboBox1.SelectedIndex = i; break; } else { this.comboBox1.SelectedIndex = -1; } } }
|