2016-05-02 128 views
1

我已經動態創建了5個下拉列表。這是從aspx.cs如何在ASP.NET中動態創建下拉控件

for (int i = 0; i < 5; i++) 
      { 
       DropDownList drop = new DropDownList(); 
       drop.ID = "dropdownlist" + i; 
       form1.Controls.Add(drop); 
       form1.Controls.Add(new LiteralControl("<br />")); 
      } 

我已經有喜歡

if (!this.IsPostBack) 
     { 
      string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; 
      using (SqlConnection con = new SqlConnection(constr)) 
      { 
       using (SqlCommand cmd = new SqlCommand("SELECT ID, Name FROM RejectedProduct")) 
       { 
        cmd.CommandType = CommandType.Text; 
        cmd.Connection = con; 
        con.Open(); 
        DropDownList1.DataSource = cmd.ExecuteReader(); 
        DropDownList1.DataTextField = "Name"; 
        DropDownList1.DataValueField = "ID"; 
        DropDownList1.DataBind(); 
        con.Close(); 
       } 
      } 
      DropDownList1.Items.Insert(0, new ListItem("Select Item for adding", "0"));} 

如何使用用於動態創建新的每次5下拉這段代碼另一個下拉代碼?

+0

使用動態控件在asp.net中是一個壞主意,因爲控件在每次回發中被破壞並且必須被重新創建。他們不會持有你在其中的價值。這是一個糟糕的主意。 –

+0

動態創建控件需要幾個步驟;你錯過了很多步驟。看看[這](http://stackoverflow.com/a/18155057/296861)的答案。如果您有具體問題,請回來再問一次。 – Win

回答

0

請查看Mysterio11的評論& Win。

填寫數據的基本思路如下。最重要的是它沒有優化。在循環中創建命令和連接是不同的想法。

 if (!this.IsPostBack) 
     { 
      DropDownList DropDownList1; 
      for (int i = 0; i < 5; i++) 
      { 
       DropDownList1 = (DropDownList)FindControl("dropdownlist" + i); 
       string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; 
       using (SqlConnection con = new SqlConnection(constr)) 
       { 
        using (SqlCommand cmd = new SqlCommand("SELECT ID, Name FROM RejectedProduct")) 
        { 
         cmd.CommandType = CommandType.Text; 
         cmd.Connection = con; 
         con.Open(); 
         DropDownList1.DataSource = cmd.ExecuteReader(); 
         DropDownList1.DataTextField = "Name"; 
         DropDownList1.DataValueField = "ID"; 
         DropDownList1.DataBind(); 
         con.Close(); 
        } 
       } 
       DropDownList1.Items.Insert(0, new ListItem("Select Item for adding", "0")); 
      } 
     } 
+0

它引發異常 異常詳細信息:System.NullReferenceException:未將對象引用設置爲對象的實例。 –

+0

@joyoares對於延遲我非常抱歉。我用來測試的代碼附加到這個[link](https://drive.google.com/open?id=0B_czp2rbfZFjbURncGljZk53X2s)並且它的工作正常。請通過它。 – lal