首頁  >  文章  >  後端開發  >  《ASP.NET》資料綁定—DropDownList、ListBox的圖文程式碼詳解

《ASP.NET》資料綁定—DropDownList、ListBox的圖文程式碼詳解

黄舟
黄舟原創
2017-03-08 13:07:201645瀏覽

    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的圖文程式碼詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn