省市联动 DropDownList控件

来源:互联网 发布:商业公司顶级域名是 编辑:程序博客网 时间:2024/05/17 03:34

1》

DropDownList控件可以使用ObjectDataSource作为数据源。但是也是可以自己手动绑定数据源。这里我们就尝试自己手动绑定数据源

首先,在WebForm页面拖入两个DropDownList控件。 给DropDownList1控件的DropDownList1.AutoPostBack 属性设置为 true;

DropDownList1.AutoPostBack = true;

这样当用户改变DropDownList1这个控件的内容的时候,即选中值的时候,就会自动提交数据,通过自动提交数据来改变DropDownList2这个控件里的值

比如DropDownList1控件里的值设置湖南,那么DropDownList2里面的值就会改变为湖南对应的地级城市。

如何实现这个功能呢? 如果用手动绑定数据源的方法来实现的话,我们可以这样做:在DropDownList1改变数据的时候,因为之前已经设置了DropDownList1.AutoPostBack = true;它会在数据改变的时候自动提交。鉴于这个原理,我们可以在某个方法中获取这个提交过来的值,比如提交过来一个‘湖南’  然后根据这个值去数据库中查找,这个湖南省份对应的地级市。然后将值显示到DropDownList2控件当中。


提示一下:如果用OjbectDataSource数据源的话,那么就将DropDownList1绑定一个OjbectDataSource数据源,将DropDownList2再绑定一个OjbectDataSource数据源,



using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using Web.BLL;namespace WebApp{    public partial class LocationList : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            if (!IsPostBack)            {                //如果是第一次加载。将DropDownList1控件绑定数据源                LocationBll bll = new LocationBll();                //数据源为这个方法(方法返回一个List泛型集合)                this.DropDownList1.DataSource = bll.GetLocationALlProvince();                //让DropDownList1这个控件显示locName这个字段的数据                this.DropDownList1.DataTextField = "locName";                //假如说要提交数据,到底是提交那个字段的值。这里设置提交数据的时候提交的是locName的值                this.DropDownList1.DataValueField = "locName";                this.DropDownList1.DataBind();            }            else            {                //既然前面设置了this.DropDownList1.DataValueField = "locName"; 那么这里获取到的也就是locName的值(例如;湖南)                string a = this.DropDownList1.SelectedItem.Text;                string b = this.DropDownList2.SelectedItem.Text;                //这里是获取到的locName对应的locId的值                string c = this.DropDownList2.SelectedItem.Value;            }               }    }}


0 0