2012-07-31 20 views
5

這是下拉我的CS文件:如何在CS文件中添加項目在下拉列表中

protected void BindDropDownList()  

    { 

     DataTable dt = new DataTable(); 
     string connString = System.Configuration.ConfigurationManager.AppSettings["EyeProject"]; 
     SqlConnection conn = new SqlConnection(connString); 


     try 
     { 
      conn.Open(); 
      string sqlStatement = "SELECT FirstName FROM tbl_UserDetails"; 
      SqlCommand sqlCmd = new SqlCommand(sqlStatement, conn); 
      SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd); 

      sqlDa.Fill(dt); 
      if (dt.Rows.Count > 0) 
      { 
       DropDownList1.DataSource =dt; 


       DropDownList1.DataTextField = "FirstName"; // the items to be displayed in the list items 

       DropDownList1.DataBind(); 
      } 
     } 
     catch (System.Data.SqlClient.SqlException ex) 
     { 
      string msg = "No Data Found To display in the DropDown List"; 
      msg += ex.Message; 
      throw new Exception(msg); 
     } 
     finally 
     { 
      conn.Close(); 
     } 


    } 



By using this one iam getting values of table Firstname values now i want to add one more item Called ALLrecords. 

How can i add it. 

this is my Aspx file 

<div class="label"> 
            Select Name: 
            <asp:DropDownList ID="DropDownList1" runat="server"> 

            </asp:DropDownList> 
           </div> 

回答

17

試試這個

DropDownList1.Items.Add(new ListItem("All Record")); 

,如果你想與增值項目,然後

DropDownList1.Items.Add(new ListItem("All Record","0")); 

//or if you want to add at particular index then 

DropDownList1.Items.Insert(0,new ListItem("All Record"));// 0 is index of item 

希望這有助於。

+0

DropDownList1.Items.Add(new ListItem(「All Record」)); iam使用這一個。在顯示所有下拉菜單中的剩餘值之後,我會從數據庫中獲取數據,即firstname。它也必須在下拉菜單中顯示,當我點擊它時。 – 2012-07-31 07:14:20

+0

首先將數據庫值與您的數據庫值綁定在一起,然後使用您所喜歡的添加或插入方法。 – 2012-07-31 07:19:07

2

在指定索引

DropDownListID.Items.Insert(0, new ListItem("Default text", "Default value") 
3
DropDownList1.Items.Insert(0,new ListItem("AllRecords","itsValue_on_dropdownlist")); // use 0 to show "ALLRecords" text on top in dropdownlist 

插入項目,我建議你應該綁定值也下拉列表。 這樣的 -

DropDownList1.DataValueField = "FirstName"; 
0

在下拉列表聲明標籤.aspx文件中像這樣 「爲addItems」 功能第一次寫的onLoad:

然後創建在CS文件 「爲addItems」 功能。

<asp:DropDownList ID="DropDownList1" runat="server" OnLoad="addDeleteItems" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"> 

protected void addItems(object sender, System.EventArgs e) 
{ 
    DropDownList ddl = (DropDownList)sender;   
    ListItem newItem = new ListItem("rose", "i"); 
    ddl.Items.Add(newItem); 
}  
相關問題