C# ComboBox的聯動操作(三層架構)_C#教程

來源:互聯網
上載者:User

項目需求:根據年級下拉框的變化使得科目下拉框綁定次年級下對應有的值

我們用三層架構的模式來實現

1.我們想和資料庫互動,我們首先得來先解決DAL資料庫互動層

01.獲得年級下拉框的資料

在GradeDAL類中

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Data.SqlClient;using System.Data;using MySchool.Model;using System.Configuration;namespace MySchool.DAL{ //資料訪問層 public class GradeDAL {  public static string Constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;  #region 獲得年級表   public DataTable SelectGrade(string gradetype)   {   //和資料庫互動   string str = "Data Source=.;initial catalog=MySchool;uid=sa";   SqlConnection con = new SqlConnection(str);   string sql = "";   if (gradetype=="")   {    sql = "select * from Grade";   }   else   {    sql = "select * from Student where GradeId in (select GradeId from Grade where GradeName='" + gradetype + "')";   }      SqlDataAdapter da = new SqlDataAdapter(sql, con);   DataSet ds = new DataSet();   //捕獲異常   try   {    da.Fill(ds, "stuInfo");   }   catch (Exception ex)   {    throw new Exception(ex.Message);   }   //返回一張表的資料   return ds.Tables["stuInfo"];  }  #endregion  #region 擷取年級資料,為在下拉框中顯示   //定義一個集合,儲存年級資訊   List<Grade> list = new List<Grade>();   #region 方法一: 以返回表的方式   public DataTable LoadCombox()   {    string sql = "select * from Grade";    DataTable dt = SQLHelper.ExecuteDataTable(sql);    return dt;   }   #endregion   #region 方法二:以返回集合的方式   public List<Grade> Loadcombox2()    {    string sql = "select * from Grade";    DataTable dt = SQLHelper.ExecuteDataTable(sql);    //方法一:    foreach (DataRow row in dt.Rows)    {     //每一個row代表表中的一行,所以一行對應一個年級對象     Grade grade = new Grade();     grade.GradeId = Convert.ToInt32(row["gradeid"]);     grade.GradeName = row["gradename"].ToString();     list.Add(grade);    }    //方法二:(使用MyTool類)    //MyTool tool=new MyTool();    //list = tool.DataTableToList<Grade>(dt);    return list;   }  #endregion   #region 方法三:要求使用using語句   public List<Grade> LoadCombox3()    {    //using的作用可以釋放資源,利於資源的回收(可以省略關閉串連)    using (SqlConnection con=new SqlConnection(Constr))    {     try     {      string sql = "select * from Grade";      SqlCommand cmd = new SqlCommand(sql,con);      con.Open();      SqlDataReader dr = cmd.ExecuteReader();      while (dr.Read())      {       Grade gr = new Grade();       gr.GradeId = Convert.ToInt32(dr["GradeId"]);       gr.GradeName=dr["GradeName"].ToString();       list.Add(gr);      }         }     catch (Exception ex)     {      throw new Exception(ex.Message);      }    }    return list;   }  #endregion   #endregion       }}

02.在商務邏輯層

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using MySchool.DAL;using System.Data;using MySchool.Model;namespace MySchool.BLL{ public class GradeBLL {  GradeDAL gradedal = new GradeDAL();  #region 擷取年級資料,為在下拉框中顯示  public DataTable SelectGrade(string gradetype)  {   return gradedal.SelectGrade(gradetype);  }  public DataTable LoadCombox()  {   return gradedal.LoadCombox();  }    public List<Grade> Loadcombox2()  {   return gradedal.Loadcombox2();  }  #endregion  public List<Grade> LoadCombox3()  {   return gradedal.LoadCombox3();  }   }}

03.在表單UI層

在Load事件中載入年級下拉框

 private void FrmSelectResult_Load(object sender, EventArgs e)  {   #region 載入年級下拉框   try   {    List<Grade> list = gradedal.LoadCombox3();    list.Insert(0, new Grade() { GradeId=-1,GradeName="--全部--" });    cboGrade.ValueMember = "GradeId";    cboGrade.DisplayMember = "GradeName";    cboGrade.DataSource = list;   }   catch (Exception ex)   {    MessageBox.Show(ex.Message);   }         #endregion   #region 載入科目下拉框   //try   //{   // list2 = subjectdal.LoadComboxSub();   // list2.Insert(0, new Subject() { SubjectId = -1, SubjectName = "--全部--" });   // cboSubject.ValueMember = "SubjectId";   // cboSubject.DisplayMember = "SubjectName";   // cboSubject.DataSource = list2;   //}   //catch (Exception ex)   //{   // MessageBox.Show(ex.Message);   //}      #endregion  }

其中在使用

獲得年級下拉框隱藏值得方法(2)
int num = Convert.ToInt32(cboGrade.SelectedValue);

載入年級下拉框時:會出現的錯誤的寫法

把cboGrade.DataSource = list;寫在
 cboGrade.ValueMember = "GradeId";
 cboGrade.DisplayMember = "GradeName";上面
即:

 #region 載入年級下拉框   try   {    List<Grade> list = gradedal.LoadCombox3();    list.Insert(0, new Grade() { GradeId=-1,GradeName="--全部--" });    cboGrade.DataSource = list;    cboGrade.ValueMember = "GradeId";    cboGrade.DisplayMember = "GradeName";           }   catch (Exception ex)   {    MessageBox.Show(ex.Message);   }         #endregion

這是就會出現下面錯誤:

在年級的SelectedIndexChanged事件中

 try   {    //根據年級取得科目資訊並綁定     #region 獲得年級下拉框隱藏值得方法(1)    Grade sub = (Grade)cboGrade.SelectedItem;    int num =sub.GradeId;    #endregion    #region 獲得年級下拉框隱藏值得方法(2)    // int num = Convert.ToInt32(cboGrade.SelectedValue.ToString());    #endregion        List<Subject> list = subjectdal.LoadComboxSub2(num);        cboSubject.ValueMember = "SubjectId";    cboSubject.DisplayMember = "SubjectName";    cboSubject.DataSource = list;           }   catch (Exception)   {    MessageBox.Show("出錯");   }

以上就是本文的全部內容,希望對大家學習C#程式設計有所協助。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.