背景:visual studio 2005 ;
实现选择省时,自动显示所属的城市列表
实现:省:dropdownlist---.ddlProvince ----AutoPostBack="True";
市:dropdowncity---ddlCity; /listbox---lbCity
代码:
数据库设计:
create database db_pro_city
go
use db_pro_city
go
create table tb_pro
(
proID int primary key,
proName varchar(50) not null
)
go
insert into tb_pro values(1,'北京')
insert into tb_pro values(2,'江苏')
insert into tb_pro values(3,'安徽')
insert into tb_pro values(4,'湖北')
go
select * from tb_pro
go
create table tb_city
(
cityID int primary key,
proID int foreign key references tb_pro(proID),
cityName varchar(50) not null
)
go
insert into tb_city values(1,1,'北京')
insert into tb_city values(2,2,'南京')
insert into tb_city values(3,2,'苏州')
insert into tb_city values(4,2,'盐城')
insert into tb_city values(5,3,'芜湖')
insert into tb_city values(6,3,'合肥')
insert into tb_city values(7,4,'黄冈')
insert into tb_city values(8,4,'湖北')
go
数据库连接DB.cs:
public static SqlConnection createCon()
{
return new SqlConnection("server=localhost\\sqlexpress;database=db_pro_city;uid=sa;pwd=hello");
}
加载页面代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//绑定省
SqlConnection con = DB.createCon();
con.Open();
SqlCommand cmdpro = new SqlCommand("select * from tb_pro", con);
SqlDataReader sdrpro = cmdpro.ExecuteReader();
this.ddlProvince.DataSource = sdrpro;
this.ddlProvince.DataTextField = "proName";
this.ddlProvince.DataValueField = "proID";
this.ddlProvince.DataBind();
sdrpro.Close();
//绑定市
SqlCommand cmdcity = new SqlCommand("select * from tb_city where proID=" + this.ddlProvince.SelectedValue, con);
SqlDataReader sdrcity = cmdcity.ExecuteReader();
this.ddlCity.DataSource = sdrcity;
this.ddlCity.DataTextField = "cityName";
this.ddlCity.DataValueField = "cityID";
this.ddlCity.DataBind();
sdrcity.Close();
con.Close();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = DB.createCon();
con.Open();
SqlCommand cmdcity=new SqlCommand("select * from tb_city where proID=" + this.ddlProvince.SelectedValue, con);
SqlDataReader sdrcity = cmdcity.ExecuteReader();
this.ddlCity.DataSource = sdrcity;
this.ddlCity.DataTextField = "cityName";
this.ddlCity.DataValueField = "cityID";
this.ddlCity.DataBind();
sdrcity.Close();
con.Close();
}
//listbox代码.循环取值,并将值添加到ListBox
SqlCommand cmdcity = new SqlCommand("select * from tb_city where proID=" + this.ddlProvince.SelectedValue, con);
SqlDataReader sdrcity = cmdcity.ExecuteReader();
while(sdrcity.Read())
{
//ListBox之text字段为:cityName第3列, value字段为:cityID第1列;
this.lbCity.Items.Add(new ListBox(sdrcity.GetStrint(2),sdrcity.GetInt32(0).ToString())
}