首先我们需要在数据库中建立两个表,一个是Province(省份)表,一个是City(城市)表。建表语句如下: 代码如下: 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; } }
Web窗体加载时执行代码: 代码如下: 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);