<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="省市县三级连接.aspx.cs" Inherits="省级连动.省市县三级连接" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
前台:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlProvince" runat="server" AutoPostBack="true"
onselectedindexchanged="ddlProvince_SelectedIndexChanged" Width="100px">
</asp:DropDownList>
<asp:DropDownList ID="ddlCity" runat="server" AutoPostBack="true"
onselectedindexchanged="ddlCity_SelectedIndexChanged" Width="100px">
</asp:DropDownList>
<asp:DropDownList ID="ddlArear" runat="server" Width="100px">
</asp:DropDownList>
</div>
</form>
</body>
</html>
后台:
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
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetProvince();
}
}
private void LoadData(string id, DropDownList ddl)
{
string strcon = "Data Source=PC-Dll;Initial Catalog=News; Persist Security Info=true;User Id=sa;Password=linlin ";
SqlConnection conn = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT A_Id,A_Name FROM T_Arear WHERE A_ParentId=@parentid ORDER BY A_Id";
cmd.Parameters.AddWithValue("@parentid",id);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
cmd.Dispose();
conn.Dispose();
ddl.DataSource = dt;
ddl.DataTextField = "A_Name";
ddl.DataValueField = "A_Id";
ddl.DataBind();
if (id=="0")
{
ListItem item = new ListItem("-------请选择-------","0");
ddl.Items.Insert(0,item);
}
}
private void GetProvince()
{
LoadData("0",this.ddlProvince);
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
string id = this.ddlProvince.SelectedItem.Value;
if (id != "0")
{
LoadData(id, this.ddlCity);
string selectid = this.ddlCity.SelectedItem.Value;
LoadData(selectid, this.ddlArear);
}
else
{
this.ddlCity.Items.Clear();
this.ddlArear.Items.Clear();
}
}
protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
{
string id = this.ddlCity.SelectedItem.Value;
LoadData(id,this.ddlArear);
}
}
}