Combox联动效果
如上图所示窗体
实现点击年级下拉框时,加载对应的科目信息
在此过程中会遇到如下问题
问题一:
步骤一:
Load事件中显示如下代码:
先绑定数据源,后绑定displaymember 和 valueMember属性
就会报错
private void SelectStudentResult_Load(object sender, EventArgs e) { //给年级下拉框赋值 List<Grade> gradeList= gradeBLL.LoadGradeInfoToCobList(); cobGradeList.DataSource = gradeList; cobGradeList.DisplayMember = "GradeName"; cobGradeList.ValueMember = "GradeId"; }
步骤二:
在年级下拉框的SelectedIndexChanged事件中加入如下代码
private void cobGradeList_SelectedIndexChanged(object sender, EventArgs e) { try { cobSubjectList.DataSource = subBLL.GetSubjectInfoByGradeID(Convert.ToInt32(cobGradeList.SelectedValue)); cobSubjectList.DisplayMember = "subjectName"; cobSubjectList.ValueMember = "subjectid"; } catch (SqlException sqlex) { throw sqlex; } catch (Exception ex) { throw ex; } }
错误信息:
下面我们来分析一下出错的原因
原因就出在代码的执行顺序上 我们可以用打断点的方式来查看
当代码执行到红框标识处时,代码块直接跳到SelectedIndexChanged事件中,此时控件的displayMember和valueMember属性还未被附上值
所以当蓝色标识框去拿年级下拉框的隐藏值时就会报错
解决方案:将load事件中的代码改为
coblist.DisplayMember
coblist.ValueMember
coblist.DataSource=list;
解决方案二:
就是用SelectedItem代替SelectedValue
Load事件中的代码不变
更改如下代码
private void cobGradeList_SelectedIndexChanged(object sender, EventArgs e) { Grade grade = (Grade)cobGradeList.SelectedItem; int gradeid = Convert.ToInt32(grade.GradeId); cobSubjectList.DataSource = subBLL.GetSubjectInfoByGradeID(gradeid); cobSubjectList.DisplayMember = "subjectName"; cobSubjectList.ValueMember = "subjectid"; }
此处是泛型集合
如果是DataTable
更改的代码为
DataRowView dr=(DataRowView)cobListGradeList.SelectedItem;
int gradeid=Convert.ToInt32(dr["gradeid"]);
不知道这些东西会不会给有需要帮助的人带来一点点提示,如有意见欢迎指出
时间: 2024-11-05 20:33:07