ComboBox控件
常用属性:Name,DropDownStyle,Items,DataSource,DisplayMember,ValueMember,Text,SelectedIndex,Selected Value,SelectedItem
常用事件:SelectedIndexChanged 选择项更改时触发事件
Items方法:用于添加对象的:Add,Insert,AddRange;用于删除对象的:Remove,RemoveAt,Clear,以及用于查找的:Contains,IndexOf
知识点1:
DropDownStyle,控制组合框的外观和功能,选项可以为Simple,DropDown,DropDownList,如下
不同模式对应的效果

知识点2:
ComboBox数据填充。
第一种方法,使用Items的Add方法,适用于项目数量不多,项目固定的情况。
第二种方法,使用DataSource,DisplayMember,ValueMember属性,适用于动态绑定的情况。
第三种方法,结合方法1和方法2,使用DisplayMember,ValueMember属性,在添加数据的时候使用dataList.ForEach(new Action<Grad>(g => comboBox1.Items.Add(g)));
使用第一种方法,可以方便的对Item进行添加和移除;
使用第二种方法,不能动态的添加和移除Item。
使用第三种方法,可以动态绑定数据,也可以动态增加和移除数据。
private void FormComboBox_Load(object sender, EventArgs e) { //方法1 comboBox1.Items.AddRange(new object[] {"一年级", "二年级", "三年级"}); DAL dAL = new DAL(); comboBox1.DisplayMember = "GradName"; comboBox1.ValueMember = "GradId"; //comboBox1.DataSource = dAL.GetAllGrad();//方法2 List<Grad> gradList = dAL.GetAllGrad(); gradList.ForEach(new Action<Grad>(g => comboBox1.Items.Add(g)));//方法3, comboBox1.SelectedIndex = 0; }
知识点3:
实现ComboBox的级联选择,下一及ComboBox的数据动态跟踪上一级ComboBox的选择。
方法:使用SelectedIndexChanged事件

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { int gradId = int.Parse(comboBox1.SelectedValue.ToString()); DAL dal = new DAL(); List<Class> classList = dal.GetClassByGrad(gradId); comboBox2.DisplayMember = "ClassName"; comboBox2.ValueMember = "ClassId"; comboBox2.DataSource = classList; }
浙公网安备 33010602011771号