use master
go
if exists(select * from sys.databases where name='MyData')
drop database MyData
go
create database MyData
go
use MyData
go
if exists(select * from sys.objects where name='Provice')
drop table provice
go
create table Provice
(
proid int primary key identity(1,1),
proname varchar(100),
upproid int
)
go
--select * from Provice
--go
insert into Provice(proname,upproid) values('河北',0)
insert into Provice(proname,upproid) values('保定',1)
insert into Provice(proname,upproid) values('张家界',1)
insert into Provice(proname,upproid) values('湖北',0)
insert into Provice(proname,upproid) values('荆州',4)
insert into Provice(proname,upproid) values('仙桃',4)
insert into Provice(proname,upproid) values('湖南',0)
insert into Provice(proname,upproid) values('长沙',7)
insert into Provice(proname,upproid) values('岳阳',7)
go
s
前台代码
<asp:DropDownList ID="ddlOne" runat="server" ontextchanged="ddlOne_TextChanged" onselectedindexchanged="Page_Load" AutoPostBack="true"></asp:DropDownList>
<asp:DropDownList ID="ddlTwo" runat="server" onselectedindexchanged="Page_Load"></asp:DropDownList>
后台代码
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Share();
CommondOne();
}
}
public string str = "";
public SqlConnection con;
protected void Share()
{
str = ConfigurationManager.ConnectionStrings["ConStr"].ToString();
con = new SqlConnection(str);
con.Open();
}
protected void CommondOne()
{
SqlCommand cmd = new SqlCommand("select * from Provice where upproid=0",con);
SqlDataReader dr = cmd.ExecuteReader();
ddlOne.Items.Clear();
ddlOne.Items.Add(new ListItem("请选择省", ""));
ddlTwo.Items.Add(new ListItem("请选择城市", ""));
if (!dr.HasRows)
{
return;
}
while (dr.Read())
{
ddlOne.Items.Add(new ListItem(dr["proname"].ToString(), dr["proid"].ToString()));
}
dr.Close();
con.Close();
}
protected void ddlOne_TextChanged(object sender, EventArgs e)
{
Share();
CommondTwo();
}
protected void CommondTwo()
{
SqlCommand cmd = new SqlCommand("select * from Provice where upproid =" + Convert.ToInt32(ddlOne.SelectedValue), con);
SqlDataReader dr = cmd.ExecuteReader();
ddlTwo.Items.Clear();
ddlTwo.Items.Add(new ListItem("请选择城市", ""));
if (!dr.HasRows)
{
return;
}
while (dr.Read())
{
ddlTwo.Items.Add(new ListItem(dr["proname"].ToString(), dr["proid"].ToString()));
}
dr.Close();
con.Close();
}