DropDownList和ListBox實(shí)現(xiàn)兩級(jí)聯(lián)動(dòng)功能,它們可以將從后臺(tái)數(shù)據(jù)庫(kù)中搜選的出來(lái)的信息加以綁定,這里要實(shí)現(xiàn)的功能是在DropDownList中選擇“省”,然后讓ListBox自動(dòng)將其省份下的“市”顯示出來(lái),這就是所謂的兩級(jí)聯(lián)動(dòng)功能,這個(gè)功能我們?cè)诤芏嘧?cè)網(wǎng)頁(yè)上看見,今天就為大家解開ASP.NET神秘的面紗。
一、設(shè)置前臺(tái)界面,在Web窗體中添加DropDownList和ListBox兩個(gè)控件。
界面圖如下所示。

二、編寫后臺(tái)代碼
在這,后臺(tái)代碼編寫在其窗體的Page_Load事件中
span style="font-family:KaiTi_GB2312;font-size:18px;"> protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack ) //判斷頁(yè)面是否第一次加載
{
SqlConnection con = DB.createConnection(); //此方法在上一篇文章中已經(jīng)介紹,調(diào)用一個(gè)已經(jīng)編寫好的創(chuàng)建數(shù)據(jù)庫(kù)連接的方法。
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事件代碼,實(shí)現(xiàn)單擊“省”,ListBox自動(dòng)添加該“省”所具有的“市”
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>
運(yùn)行文件,效果圖如下所示

這里河北省的城市我沒有添加完整,只是為了實(shí)現(xiàn)兩級(jí)聯(lián)動(dòng)的功能,相比前兩篇文章中Web控件GridView和Repeater的使用,GridView和Repeater功能雖然是相當(dāng)強(qiáng)大,但是不同的控件有不同的用途,在這里,殺雞焉用牛刀?
您可能感興趣的文章:- asp.net省市三級(jí)聯(lián)動(dòng)的DropDownList+Ajax的三種框架(aspnet/Jquery/ExtJs)示例
- ASP.NET MVC下拉框聯(lián)動(dòng)實(shí)例解析
- asp.net DropDownList實(shí)現(xiàn)二級(jí)聯(lián)動(dòng)效果
- asp.net下使用AjaxPro實(shí)現(xiàn)二級(jí)聯(lián)動(dòng)代碼
- asp.net DropDownList 三級(jí)聯(lián)動(dòng)下拉菜單實(shí)現(xiàn)代碼
- asp.net兩級(jí)聯(lián)動(dòng)(包含添加和修改)
- 適用與firefox ASP.NET無(wú)刷新二級(jí)聯(lián)動(dòng)下拉列表
- ASP.NET實(shí)現(xiàn)級(jí)聯(lián)下拉框效果實(shí)例講解
- ASP.NET Ajax級(jí)聯(lián)DropDownList實(shí)現(xiàn)代碼
- jQuery+Asp.Net實(shí)現(xiàn)省市二級(jí)聯(lián)動(dòng)功能的方法