1. 程式人生 > >《ASP.NET》數據綁定—DropDownList、ListBox

《ASP.NET》數據綁定—DropDownList、ListBox

第一次 n) protected add 博客 on() 級聯 沒有 是否

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功能盡管是相當強大,可是不同的控件有不同的用途。在這裏,殺雞焉用牛刀?


《ASP.NET》數據綁定—DropDownList、ListBox