1. 程式人生 > >C#,winform形式下 2個combobox 互相聯動---資料庫access

C#,winform形式下 2個combobox 互相聯動---資料庫access

參考文章:

privatevoid Form1_Load(object sender, EventArgs e)
        {
            SqlConnection con
=new SqlConnection(conn);
            con.Open();
            SqlCommand cmd
=new SqlCommand("select * from department",con);          
            SqlDataAdapter sda
=new SqlDataAdapter(cmd);
            DataTable dt

=new DataTable();
            sda.Fill(dt);
            con.Close();
            comboBox1.DataSource
= dt;
            comboBox1.DisplayMember
="department";
            comboBox1.ValueMember
="departmentId";

        }

       
privatevoid comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
           
if (comboBox1.SelectedIndex>-1)
            {
                DataRowView drv
= (DataRowView)comboBox1.SelectedItem;
               
int id = Convert.ToInt32(drv.Row["departmentId"].ToString());
                SqlConnection con
=new SqlConnection(conn);
                con.Open();
                SqlCommand cmd
=new SqlCommand("select * from major where departmentId='"+ id +"'", con);
                SqlDataAdapter sda
=new SqlDataAdapter(cmd);            
                DataTable dt
=new DataTable();
                sda.Fill(dt);
                comboBox2.DataSource
= dt;
                comboBox2.DisplayMember
="major";
                comboBox2.ValueMember
="majorId";
            }

2,

ComboBox的SelectionChangeCommitted事件

實現方案:

 在ComboBox的SelectionChangeCommitted事件 寫 聯動取數:

  private  void comBox_subject_SelectionChangeCommitted(object sender, System.EventArgs e)
        {
            if (comBox_subject.SelectedIndex > -1)
            {
                DataRowView drv = (DataRowView)comBox_subject.SelectedItem;
                String check_subject = drv.Row["學科"].ToString();

                string connectionStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.Windows.Forms.Application.StartupPath + "/teachdb.mdb";
                OleDbConnection conn = new OleDbConnection(connectionStr);
                conn.Open();


                string strsubject = "select distinct 出版社 from presstable where 學科='" + check_subject + "'";
                OleDbDataAdapter MyAdapter1 = new OleDbDataAdapter(strsubject, conn);

                DataSet ds = new DataSet();
                MyAdapter1.Fill(ds, "press");

                comBox_Press.DataSource = ds.Tables["press"].DefaultView;
                comBox_Press.DisplayMember = "出版社";
                comBox_Press.ValueMember = "出版社";

                conn.Close();


            }
        }

 3

今天工作中遇到一個頭疼到問題就是兩個comboBox互相聯動繫結,開始用comboBox1_SelectedIndexChanged事件,結果兩個comboBox不停的相互繫結,死迴圈了

後來發現微軟還提供了一個comboBox1_DropDownClosed事件:當關閉組合框下拉部分時發生,當用程式改變SelectedIndex時就不會出現兩個comboBox相互改對方到Index並觸發comboBox1_SelectedIndexChanged

後來將SelectedIndexChanged事件全部換成DropDownClosed,就可以實現兩個comboBox互相聯動了;

TextChanged事件和TextUpdate也是一個對用程式改變其值敏感,一個不敏感。