DropDownList和ListBox實現兩級聯動功能,它們可以將從後台數據庫中搜選的出來的信息加以綁定,這裡要實現的功能是在DropDownList中選擇“省”,然後讓ListBox自動將其省份下的“市”顯示出來,這就是所謂的兩級聯動功能,這個功能我們在很多注冊網頁上看見,今天就為大家解開ASP.NET神秘的面紗。
一、設置前台界面,在Web窗體中添加DropDownList和ListBox兩個控件。
界面圖如下所示。

二、編寫後台代碼
在這,後台代碼編寫在其窗體的Page_Load事件中
<span style="font-family:KaiTi_GB2312;font-size:18px;"> 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();
}
}</span>
編寫DropDownList1_SelectedIndexChanged事件代碼,實現單擊“省”,ListBox自動添加該“省”所具有的“市”
<span style="font-family:KaiTi_GB2312;font-size:18px;"> 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()));
}
}</span>
運行文件,效果圖如下所示

這裡河北省的城市我沒有添加完整,只是為了實現兩級聯動的功能,相比前兩篇文章中Web控件GridView和Repeater的使用,GridView和Repeater功能雖然是相當強大,但是不同的控件有不同的用途,在這裡,殺雞焉用牛刀?