实现效果:
点击年级下拉框值时,获取科目下拉框值
一:加载年级下拉框值
GradeDAL层:
//检索所有年级名称集合,返回的是泛型集合List<Grade> public List<Grade> GetAllGrade() { string sql = "select * from Grade"; //将sql转成内存中的一张表 DataTable dt = SQLHelper.ExecuteDataTable(sql); MyTool tool = new MyTool(); //dt转成list List<Grade> list = tool.DataTableToList<Grade>(dt); return list; }
GradeBLL层:
//植入DAL层的对象 GradeDAL gradeDal=new GradeDAL(); public List<Grade> GetAllGrade() { return gradeDal.GetAllGrade(); }
UI层:
private void frmSelectResult_Load(object sender, EventArgs e) { //清空 cboSubject.DropDownHeight = 106; GradeBLL gradeBll = new GradeBLL(); //对年级下拉框绑定数据 List<Grade> list = gradeBll.GetAllGrade(); cboGrade.ValueMember = "GradeId"; cboGrade.DisplayMember = "GradeName"; cboGrade.DataSource = list; // flag = true; }
二:根据年级编号,去加载科目下拉框数据
1.在DAL层写一个根据年级编号获取科目集合的方法
SubjectDAL层:
public List<Subject> GetAllSubject(int id) { string sql = "select * from Subject where GradeId=@Id"; SqlParameter para = new SqlParameter("@Id",id); DataTable dt = SQLHelper.ExecuteDataTable(sql,para); MyTool tool = new MyTool(); List<Subject> list= tool.DataTableToList<Subject>(dt); return list; }
2.Bll层做数据传递
SubjectDAL subjectDal = new SubjectDAL(); public List<Subject> GetAllSubject(int id) { return subjectDal.GetAllSubject(id); }
3.UI层 下拉框选中项发生改变的事件:SelectedIndexChanged
SubjectBLL subBll = new SubjectBLL(); private void cboGrade_SelectedIndexChanged(object sender, EventArgs e) { // if (flag) // { int selectid = Convert.ToInt32(cboGrade.SelectedValue); List<Subject> list = subBll.GetAllSubject(selectid); cboSubject.ValueMember = "SubjectId"; cboSubject.DisplayMember = "SubjectName"; cboSubject.DataSource = list; //} }
注:
解决方案:
1.若碰到IConvertable错误的时候,如果是下拉框数据绑定,规避的方案:
将DataSource=泛型集合,调整到最后一行
2.用标记,在Load 和SelectedIndexChanged之外,定义一个bool类型变量。
然后在Load中设置成True,在SelectedIndexChanged中判定fla
当年级下拉框选择一个没有科目的年级后,科目下拉框还是占用了上次有数据的下拉框个数!
解析:可以使用 cboSubject.DropDownHeight = 106