最近项目使用WinForm,开始对WinForm进行一些学习,主要是对常用控件的使用。一些简单的,像什么TextBox,Label,CheckBox,和WebForm差不多,就不用说了,今天先来看看ComboBox。
1.概述
ComboBox有点类似于WebForm下的DropDownList,它能够实现和DropDownList同样的效果,还能实现一些DropDownList没有的效果,通过设置DropDownStyle属性,可以得到三种不同的效果。
Simple: 可从下面列表中选择,也可直接输入
DropDown: 可从下拉列表中选择,也可直接输入
DropDownList: 只能从下拉列表中选择
2.数据邦定
可以通过Items集合来添加
this.comboBox1.Items.Add("亚洲");
this.comboBox1.Items.Add("非洲");
this.comboBox1.Items.Add("欧洲");
this.comboBox1.Items.Add("美洲");
this.comboBox1.Items.Add("非洲");
this.comboBox1.Items.Add("欧洲");
this.comboBox1.Items.Add("美洲");
但是这样添加后,只有Text没有Value,通常我们将数据库中的ID和Description都邦定到DropDownList上,显示给用户看的是Description,而取值时是取的ID,这时候应该怎么办呢?还是有办法的:
//构造一个DataTable
DataTable dt = new DataTable();
dt.Columns.Add("ID",typeof(string));
dt.Columns.Add("Continent",typeof(string));
dt.Rows.Add(new string[]{"1","亚洲"});
dt.Rows.Add(new string[]{"2","非洲"});
dt.Rows.Add(new string[]{"3","欧洲"});
dt.Rows.Add(new string[]{"4","美洲"});
//实现邦定
this.comboBox1.ValueMember = "ID";
this.comboBox1.DisplayMember = "Continent";
this.comboBox1.DataSource = dt;
DataTable dt = new DataTable();
dt.Columns.Add("ID",typeof(string));
dt.Columns.Add("Continent",typeof(string));
dt.Rows.Add(new string[]{"1","亚洲"});
dt.Rows.Add(new string[]{"2","非洲"});
dt.Rows.Add(new string[]{"3","欧洲"});
dt.Rows.Add(new string[]{"4","美洲"});
//实现邦定
this.comboBox1.ValueMember = "ID";
this.comboBox1.DisplayMember = "Continent";
this.comboBox1.DataSource = dt;
这样就能通过SelectedValue来取得当前选中的值了,取描述直接取Text.
3.