1. 程式人生 > >ASP.NET------DropDownList的使用方法

ASP.NET------DropDownList的使用方法

第一種少量自定義資料時:

.aspx中的程式碼:

<asp:DropDownList ID="DropDownList1" runat="server">
                   <asp:ListItem Value="2">男</asp:ListItem>
                   <asp:ListItem Selected="True" Value="1">女</asp:ListItem>
               </asp:DropDownList>

.cs中的程式碼: 注意後臺取值有取文字和編號兩種
 this.DropDownList1.SelectedItem.Text   //取文字 既男女
  this.DropDownList1.SelectedValue.ToString()  //取編號 
第二種從資料庫中取資料進行繫結:
  DataSet dc= new DataSet();  

            sqlStr = "select book_class_id,book_class_name from book_class";


            dc = CC.GetDataSet(sqlStr, "00");   //取出資料放入表中,這裡的CC是我自己的一個公共類 ,反正這裡是取出資料放到一個表中就行了,後面給出常用公共類的程式碼
            this.DropDownList1.DataSource = dc.Tables[0];
            this.DropDownList1.DataTextField = "book_class_name"; //繫結文字對應的欄位
            this.DropDownList1.DataValueField = "book_class_id";       //繫結編號對應的欄位
            this.DropDownList1.DataBind();

後臺.cs中取資料的方法同第一種方法

特殊:給DropDownList設預設值

   this.DropDownList1.SelectedValue = 3;   // 3是編號
       this.DropDownList1.Items.FindByText(“計算機”).Selected = true;  //計算機是文字
 this.DropDownList1.Items.FindByValue("3").Selected = true; // 3是編號 

新增預設選項

  this.DropDownList1.Items.Insert(0, new ListItem("---選擇型別---", "0"));
            this.DropDownList1.SelectedIndex = 0;



點選檢視Web開發常用方法公共類