复制代码 代码如下:
Create Table Province
(
ProID int primary key,
ProName varchar(20) not null
)
Create Table City
(
CityID int primary key,
ProID int foreign key references Province(ProID),
CityName varchar(20)
)
Insert into Province values('1','北京')
Insert into Province values('2','河北')
Insert into Province values('3','山东')
insert into City values('1','1','海淀')
insert into City values('2','1','丰台')
insert into City values('3','1','大兴')
insert into City values('4','2','衡水')
insert into City values('5','2','廊坊')
insert into City values('6','2','保定')
insert into City values('7','3','济南')
insert into City values('8','3','烟台')
insert into City values('9','3','青岛')
复制代码 代码如下:
public class DB
{
//连接数据库的字符串
public static SqlConnection CreateConnection()
{
SqlConnection con = new SqlConnection("Data Source=. ;Initial Catalog=test;uid=sa;pwd=123456;");
return con;
}
}
复制代码 代码如下:
protected void Page_Load(object sender, EventArgs e)
{
//如果窗体是第一次加载
if (!this.IsPostBack)
{
//绑定省份
SqlConnection con = DB.CreateConnection();
//打开数据库连接
con.Open();
SqlCommand cmdProvince = new SqlCommand("select * from Province", con);
SqlDataReader sdrProvince = cmdProvince.ExecuteReader();
//将sdrProvince中的内容绑定到ddlProvince下拉列表中
this.ddlProvince.DataSource = sdrProvince;
//需要显示的数据表Province中的内容
this.ddlProvince.DataTextField = "ProName";
//需要显示的数据表Province中的主键
this.ddlProvince.DataValueField = "ProID";
this.ddlProvince.DataBind();
sdrProvince.Close();
//关闭数据库连接
con.Close();
}
}
复制代码 代码如下:
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = DB.CreateConnection();
//打开数据库连接
con.Open();
//绑定城市
SqlCommand cmdCity = new SqlCommand("select * from City where ProID=" + this.ddlProvince.SelectedValue, con);
SqlDataReader sdrCity = cmdCity.ExecuteReader();
//将sdrCity中的内容绑定到ddlCity下拉列表中
this.ddlCity.DataSource = sdrCity;
//需要显示的数据表City中的内容
this.ddlCity.DataTextField = "CityName";
//需要显示的数据表City中的主键
this.ddlCity.DataValueField = "CityID";
this.ddlCity.DataBind();
sdrCity.Close();
//关闭数据库连接
con.Close();
}
新闻热点
疑难解答
图片精选