ComboBox简写为:cmb
主要属性:
DropDownStyle
如果想让用户只能点选,不能用键盘输入,则设为DropDownList
ComboBox.SelectionChangeCommitted 事件仅当用户更改组合框选择时(用鼠标点选),才会引发 SelectionChangeCommitted。不要使用 SelectedIndexChanged 或 SelectedValueChanged 来捕获用户更改,因为以编程方式更改选择时,也会引发这些事件。
设置新的 ValueMember 属性会引发 ValueMemberChanged 和SelectedValueChanged 事件。
从数据库中取数据并添充到comboBox中(同时介绍ValueMember 属性),代码如下:
cmbUser.DataSource = sqlDS.Tables[0];
cmbUser.DisplayMember = "UserName"; //display context
cmbUser.ValueMember = "UserId"; //real context
there is a table named user
UserId UserName
001 tom
002 jack
003 marry
004 jack
when the programme is running,'tom','jack','marry','jack'will displayed in the comboBox,you clicked 'jack'(the first 'jack') the result is:
cmbUser.SelectedValue.ToString() = 002
cmbUser.Text = jack;
也可以将一个ArrayList绑定到comboBox代码如下:
可以把每行数据看成数据库中的一条记录,先自定义一个类保存每条记录:
public class UserIntType
{
private string _display;
private string _val;
public UserIntType(string display, string val)
{
this._display = display;
this._val = val;
}
public string DisplayName
{
get { return this._display; }
}
public string ValueName
{
get { return this._val; }
}
}
/// <summary>
/// 初始化Cmb
/// </summary>
private void InitCmb()
{
ArrayList aryFld = new ArrayList();
aryFld.Add(new UserIntType("已回报金额", "sumRM"));
aryFld.Add(new UserIntType("应回报金额", "sumSR"));
cmbFieldHb.DataSource = aryFld;
cmbFieldHb.DisplayMember = "DisplayName";
cmbFieldHb.ValueMember = "ValueName";
}
//引用
fld=cmbFieldHb.SelectedValue.ToString()
若DropDownStyle=DropDownList,则cmb.text初始为空,可以cmb.SelectedIndex = 0;来选择初始值.