一、设置前台界面,在Web窗体中添加DropDownList和ListBox两个控件。
界面图如下所示。

二、编写后台代码
在这,后台代码编写在其窗体的Page_Load事件中
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack ) //判断页面是否第一次加载
{
SqlConnection con = DB.createConnection(); //此方法在上一篇文章中已经介绍,调用一个已经编写好的创建数据库连接的方法。
SqlCommand cmd = new SqlCommand("select * from province",con);
SqlDataReader sdr = cmd.ExecuteReader();
this.DropDownList1.DataTextField = "proName";
this.DropDownList1.DataValueField = "proID"; //主键字段
this.DropDownList1.DataSource = sdr;
this.DropDownList1.DataBind();
sdr.Close();
}
}编写DropDownList1_SelectedIndexChanged事件代码,实现单击“省”,ListBox自动添加该“省”所具有的“市”
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
this.ListBox1.Items.Clear();
SqlConnection con2 = DB.createConnection();
SqlCommand cmd1 = new SqlCommand("select * from city where proID=" + this.DropDownList1.SelectedValue, con2);
SqlDataReader sdr1 = cmd1.ExecuteReader();
while (sdr1.Read())
{
this.ListBox1.Items.Add(new ListItem(sdr1.GetString(2),sdr1.GetInt32(0).ToString()));
}
}运行文件,效果图如下所示
