ASP.NET——两个下拉框来实现动态联动

介绍:

      在网页中。我们常常会遇到下图中的情况。首先在下拉框中选择所在的省。选择之后,第二个下拉框会自己主动载入出该省中的市。这样设计极大的方便了用户的查找。那这是怎样实现的呢?



1、建立数据库

“省”表


“市”表



2、加入控件


3、两个下拉框分别绑定数据源

      protected void Page_Load(object sender, EventArgs e)
        {
            //推断是否第一次进入页面。假设是,则绑定数据库。假设不是,则无需绑定。

if (!this.IsPostBack) { //绑定省 SqlConnection con = DB.createConnection(); con.Open(); string cmdText = "select* from province"; SqlCommand cmd = new SqlCommand(cmdText, con); SqlDataReader sdr = cmd.ExecuteReader(); this.DropDownList1.DataSource = sdr; this.DropDownList1.DataTextField = "proName";//文本内容 this.DropDownList1.DataValueField = "proID"; //数据源字段 this.DropDownList1.DataBind(); sdr.Close(); //绑定市 string cmdCityText = "select* from city where proID=" + this.DropDownList1.SelectedValue; SqlCommand cmdCity = new SqlCommand(cmdCityText, con); sdr = cmdCity.ExecuteReader(); //剩下部分与绑定省相似,略 //关闭连接 con.Close(); } }


到这里。两个文本框都已经载入到各自的数据。剩下的就是动态联动了。

4、当我们更改第一个下拉框中的内容后,会触发第一个文本框的SelectedIndexChanged事件。将第一个下拉框的proID(省的ID)作为參数,就可以查到其市的内容。

详细代码例如以下:

 protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //省的ID
            string proID = this.DropDownList1.SelectedValue;
            SqlConnection con = DB.createConnection();
            con.Open();

            SqlCommand cmd = new SqlCommand("select * from city where proID=" + proID, con);
            SqlDataReader sdr = cmd.ExecuteReader();
            //绑定
            this.DropDownList2.DataSource = sdr;
            this.DropDownList2.DataTextField = "cityName";
            this.DropDownList2.DataValueField = "cityID";
            this.DropDownList2.DataBind();
            sdr.Close();
            con.Close();
        }


       这样。我们就能够实现动态联动了。

这种动态联动,一般由多个下拉框组成一组菜单,比方上面用到的两个下拉框。下拉菜单之间有联动的关系。

当上级的选中项发生改变时,下级会依据上级中的选中项显示对应的内容。

      尽管仅仅是一个小技巧或者说是小的需求,但当数据量特别大时。它的功能就不可小视了。上次期末考试导考生的时候,可能仅仅是一个页面忽略了这个功能,结果导致工作量大大添加。

      用了动态联动之后。当面对庞大的数据或复杂的分类时,页面的载入速度也不会受到影响,也方便了用户找到。


版权声明:本文博客原创文章,博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/mfrbuaa/p/4603594.html