前台
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<asp:DropDownList ID="Dropprovince" runat="server"
onselectedindexchanged="Dropprovince_SelectedIndexChanged"
AutoPostBack="True">
</asp:DropDownList>
</td>
<td>
<asp:DropDownList ID="Dropcity" runat="server" AutoPostBack="True"
onselectedindexchanged="Dropcity_SelectedIndexChanged">
</asp:DropDownList>
</td>
<td>
<asp:DropDownList ID="Droparea" runat="server">
</asp:DropDownList>
</td>
</tr>
</table>
</div>
</form>
后台
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace 省市选择器
{
public partial class WebForm1 : System.Web.UI.Page
{
string str = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "select * from province";
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
Dropprovince.DataSource = dt;
Dropprovince.DataTextField = "province";
Dropprovince.DataValueField = "provinceID";
Dropprovince.DataBind();
Dropcity.Items.Add("--请选择市--");
Droparea.Items.Add("--请选择地区--");
}
}
protected void Dropprovince_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con= new SqlConnection(str);
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "select * from city where father=@father ";
cmd.Parameters.AddWithValue("@father",Dropprovince.SelectedItem.Value);
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
Dropcity.DataSource = dt;
Dropcity.DataTextField = "city";
Dropcity.DataValueField = "cityID";
Dropcity.DataBind();
}
protected void Dropcity_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "select * from area where father=@father";
cmd.Parameters.AddWithValue("@father", Dropcity.SelectedItem.Value);
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
Droparea.DataSource = dt;
Droparea.DataTextField = "area";
Droparea.DataValueField = "areaID";
Droparea.DataBind();
}
}
}