DropDownList控件实现省市联动

来源:互联网 发布:js parsefloat 编辑:程序博客网 时间:2024/06/06 09:50

        在网站注册的页面上经常要选择注册地点,如果改变省的名称就能出现对应的市级的名称,将为用户带来很大的方便,下面就将我的实现过程给大家看一下

        首先,建立数据库“Place”,表里面的内容如下图所示:



窗体布局如下图所示:

下面是实现代码:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data.SqlClient;using System.Data;namespace 省市联动{    public partial class 省市联动 : System.Web.UI.Page    {        string strCon = "server=.;database=Place;uid=sa;pwd=123456";        protected void Page_Load(object sender, EventArgs e)        {            //DropDownList1.Text = "北京市";            if (!IsPostBack)            {                               SqlConnection sqlcon = new SqlConnection(strCon);                string sqlstr = "select * from Province";                string strCity = "select * from City where Province = '北京市'";                SqlDataAdapter myda = new SqlDataAdapter(sqlstr, strCon);                SqlDataAdapter mydaCity = new SqlDataAdapter(strCity, sqlcon);                DataSet myds = new DataSet();                DataSet mydsCity = new DataSet();                sqlcon.Open();                myda.Fill(myds);                mydaCity.Fill(mydsCity);                DropDownList1.DataSource = myds;                DropDownList1.DataValueField = "ProvinceName";                DropDownList1.DataBind();                DropDownList2.DataSource = mydsCity;                DropDownList2.DataValueField = "CityName";                DropDownList2.DataBind();                sqlcon.Close();            }        }        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)        {            SqlConnection sqlcon = new SqlConnection(strCon);            string sqlstr = "select * from City where Province = '" + DropDownList1.SelectedValue.Trim() + "'";            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);            DataSet myds = new DataSet();            sqlcon.Open();            myda.Fill(myds);            DropDownList2.DataSource = myds;            DropDownList2.DataValueField = "CityName";            DropDownList2.DataBind();            sqlcon.Close();        }    }}

接下来运行就可以了