当我们在做ComboBox的联动的时候飞一般的敲出自认为完美的代码。在运行的时候突然变得不完美了。

比如:

装13失败后的逆袭(ComboBox的联动)-LMLPHP

如果发生了这种情况会不会就卡磁了呢

当然不会作为程序猿的我们考的是我们聪明的大脑,当然会想出解决办法。

接下来我们来看一下解决方法:

(1)将DataSource=泛型集合,调整到最后一行

 private void Form1_Load(object sender, EventArgs e)
{
cboSubject.DropDownHeight = ; cboGrade.ValueMember = "gradeId";
cboGrade.DisplayMember = "gradeName";
//对年级下拉框绑定数据
List<Greade> list = gradebll.getAllGradeList();
cboGrade.DataSource = list; }

(2)在Load 和SelectedIndexChanged之外,定义一个bool类型变量。

然后在Load中设置成True,在SelectedIndexChanged中判定flag

 private bool flag;
private void Form1_Load(object sender, EventArgs e)
{
cboSubject.DropDownHeight = ; List<Greade> list = gradebll.getAllGradeList();
cboGrade.DataSource = list; cboGrade.ValueMember = "gradeId";
cboGrade.DisplayMember = "gradeName"; flag = true;
} private void cboGrade_SelectedIndexChanged(object sender, EventArgs e)
{
if (flag)
{
int selectid = Convert.ToInt32(cboGrade.SelectedValue);
List<Subject> list = subBll.getAllSubjectByGradeId(selectid);
cboSubject.DataSource = list;
cboSubject.ValueMember = "subjectId";
cboSubject.DisplayMember = "subjectName";
}
}
05-11 09:39