日期:2014-05-18 浏览次数:21018 次
private void Main_Load(object sender, EventArgs e) { BindComboBox(); } private void BindComboBox() { DataTable dataTable = new DataTable(); //组织数据源,这一块需要换成从DB捞取的,就不写了 dataTable.Columns.Add("ID"); dataTable.Columns.Add("UsName"); for (int i = 0; i < 3; i++) { DataRow newRow = dataTable.NewRow(); if (i == 0) { newRow["ID"] = "1"; newRow["UsName"] = "张三"; } else if (i == 1) { newRow["ID"] = "2"; newRow["UsName"] = "李四"; } else if (i == 2) { newRow["ID"] = "3"; newRow["UsName"] = "小名"; } dataTable.Rows.Add(newRow); } dataTable.AcceptChanges(); //注册事件 comboBox1.SelectedValueChanged += new EventHandler(comboBox1_SelectedValueChanged); //绑定数据源 comboBox1.DisplayMember = "UsName"; comboBox1.ValueMember = "ID"; comboBox1.DataSource = dataTable; } private void comboBox1_SelectedValueChanged(object sender, EventArgs e) { if (comboBox1.SelectedValue != null) this.textBoxMain.Text = comboBox1.SelectedValue.ToString(); }