ComBox 控件的两级联动

ComBox 控件的两级联动_第1张图片


这是主窗体 用MySchool 来做一个例子 第一个combox绑定的是Grade表 第二个是Subject表


运行后的效果如下:




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;

namespace 两级联动
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
       //窗体事件
        private void Form1_Load(object sender, EventArgs e)
        {
            string strcon = "Data Source=.;Initial Catalog=MySchool;Integrated Security=True";
            SqlConnection con = new SqlConnection(strcon);
            string sql = "select * from grade";
            SqlDataAdapter da = new SqlDataAdapter(sql, con);
            DataSet ds = new DataSet();
            da.Fill(ds,"gradeinfo");
            cboGrade.DataSource = ds.Tables["gradeinfo"];
            cboGrade.DisplayMember = "gradename";
            cboGrade.ValueMember = "gradeid";
          
        }
        
        //双击第一个控件的事件
        private void cboGrade_SelectedIndexChanged(object sender, EventArgs e)
        {
           
                string strcon = "Data Source=.;Initial Catalog=MySchool;Integrated Security=True";
                SqlConnection con = new SqlConnection(strcon);
                con.Open();
                string gradename = cboGrade.Text;
                int gradeid = idbyname(gradename);
                string sql = "select * from subject where gradeid =@gradeid";
                SqlParameter para = new SqlParameter("@gradeid", gradeid);
                SqlCommand com = new SqlCommand(sql, con);
                com.Parameters.Add(para);
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = com;
                DataSet ds = new DataSet();
                da.Fill(ds, "subjectinfo");
                cboSubject.DataSource = ds.Tables["subjectinfo"];
                cboSubject.DisplayMember = "subjectname";
                cboSubject.ValueMember = "subjectid";
           

        }
        //通过科目名字获取科目id
        public int idbyname(string name)
        {
            string strcon = "Data Source=.;Initial Catalog=MySchool;Integrated Security=True";
            SqlConnection con = new SqlConnection(strcon);
            string sql = "select gradeid from grade where gradename='" + name + "'";
            SqlCommand com = new SqlCommand(sql, con);
            con.Open();
            int gradeid = Convert.ToInt32(com.ExecuteScalar());
            if (gradeid>0)
            {
                 return gradeid;
            }
            return 0;
        }

    }
}

你可能感兴趣的:(ComBox 控件的两级联动)