ASP.NET用DropDownList控件来实现省市联动--C#,附SQL2000语句
html代码:
</head>
<body>
<form id="form1" runat="server">
<div>
省:
<asp:DropDownList ID="ddlProvince" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlProvince_SelectedIndexChanged">
</asp:DropDownList><br/>
市:
<asp:DropDownList ID="ddlCity" runat="server">
</asp:DropDownList>
</div>
</form>
</body>
</html>
cs代码:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class Province_City : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind();
}
}
private void Bind()//初始化
{
SqlConnection sqlcon = new SqlConnection("server=.;database=RegisterTest;uid=sa;pwd=;");
sqlcon.Open();
//先初始化省
SqlCommand sqlcmdpro = new SqlCommand("select * from province", sqlcon);
SqlDataReader sdrpro = sqlcmdpro.ExecuteReader();
this.ddlProvince.DataSource = sdrpro;
this.ddlProvince.DataTextField = "p_name";//显示的值
this.ddlProvince.DataValueField = "p_id";//主键
this.ddlProvince.DataBind();
sdrpro.Close();
//初始化市
SqlCommand sqlcmdcity = new SqlCommand("select * from city where p_id = '" + this.ddlProvince.SelectedValue + "'", sqlcon);
SqlDataReader sdrcity = sqlcmdcity.ExecuteReader();
this.ddlCity.DataSource = sdrcity;
this.ddlCity.DataTextField = "c_name";
this.ddlCity.DataValueField = "c_id";
this.ddlCity.DataBind();
sdrcity.Close();
sqlcon.Close();
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)//DropDownList选中(改变)产生的事件
{
string p_id = this.ddlProvince.SelectedValue;
SqlConnection sqlcon = new SqlConnection("server=.;database=RegisterTest;uid=sa;pwd=;");
sqlcon.Open();
SqlCommand sqlcmdcity = new SqlCommand("select * from city where p_id = '" + p_id + "'", sqlcon);
SqlDataReader sdrcity = sqlcmdcity.ExecuteReader();
this.ddlCity.DataSource = sdrcity;
this.ddlCity.DataTextField = "c_name";
this.ddlCity.DataValueField = "c_id";
this.ddlCity.DataBind();
sdrcity.Close();
sqlcon.Close();
}
}
SQL语句:
create database RegisterTest
use RegisterTest
create table province
(
p_id varchar(2) primary key,
p_name varchar(20)
)
create table city
(
c_id varchar(5) primary key,
p_id varchar(2) foreign key references province(p_id),
c_name varchar(10)
)