参考文章:http://blog.csdn.net/lubiaopan/article/details/5915774
绑定数据源:
private void button2_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
DataColumn column;
DataRow row;
column = new DataColumn("Name");
table.Columns.Add(column);
column = new DataColumn("Value");
table.Columns.Add(column);
row = table.NewRow();
row["Name"] = "1";
row["Value"] = "张三";
table.Rows.Add(row);
row = table.NewRow();
row["Name"] = "2";
row["Value"] = "李四";
table.Rows.Add(row);
//调用comboBox1_SelectedValueChanged(
//comboBox1.DataSource = table;
//comboBox1.DisplayMember = "Name";
//comboBox1.ValueMember = "Value";
//调用comboBox1_SelectedIndexChanged
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Value";
comboBox1.DataSource = table;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text= comboBox1.SelectedValue.ToString();
}
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
//textBox1.Text= comboBox1.SelectedValue.ToString();
}
当使用SelectedIndexChanged时,ValueMember在DataSource前进行赋值,当使用SelectedValueChanged时,ValueMember在DataSource后进行赋值。
下拉样式:
//comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;//不允许输入的下拉框
comboBox1.DropDownStyle = ComboBoxStyle.DropDown;//允许输入的下拉框
comboBox1.Items.Add("1");
comboBox1.Items.Add("2");
comboBox1.Items.Add("3");
comboBox1.Items.Add("4");
comboBox1.Items.Add("5");
comboBox1.Items.Add("6");
comboBox1.SelectedIndex = 0;//设置默认值
//comboBox1.Text = "1";//这样也可以设置默认值
//删除指定元素
//comboBox1.Items.Remove("1");
//通过索引删除制定元素
//comboBox1.Items.RemoveAt(0);
//comboBox1.Items.RemoveAt(comboBox1.Items.IndexOf("1"));
//删除所有元素
comboBox1.Items.Clear();
comboBox1.Text = "";
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = comboBox1.SelectedItem.ToString();
}