asp.net中的动态下拉列表

问题描述:

我在运行时创建了一个下拉列表,当点击一个按钮时,我又敲了另一个按钮,从动态下拉列表中获取选定的文本。当我尝试从下拉列表中检索选定的文本时,对象引用未设置,以下是我的代码。asp.net中的动态下拉列表

TableRow tr; 
    TableCell tc; 
    DropDownList dp; 
    TextBox txt; 
    protected void Button1_Click(object sender, EventArgs e) 
    { 

     int no = int.Parse(TextBox1.Text); 
     for (int i = 0; i < no; i++) 
     { 
      tr = new TableRow(); 
      tr.BorderStyle = BorderStyle.Groove; 
      for (int j = 0; j < 1; j++) 
      { 
       tc = new TableCell(); 
       tc.BorderStyle = BorderStyle.Groove; 
       dp = new DropDownList(); 
       //form1.Controls.Add(dp); 
       txt = new TextBox(); 
       dp.Items.Add("hello"); 
       tc.Controls.Add(dp); 
       tc.Controls.Add(txt); 
       tr.Cells.Add(tc); 
      } 

      Table1.Rows.Add(tr); 

     } 
    } 
    protected void Button2_Click(object sender, EventArgs e) 
    { 

     TextBox1.Text =((DropDownList)this.FindControl("dp")).SelectedItem.Text; 


    } 

你不能这样做。请记住,在每个请求中,您将获得一个新页面对象新的副本,其中包含所有控件。您动态添加的任何控件必须每次都以相同方式添加,否则它将不存在。

在这种情况下,您单击按钮时添加一次。当你点击button2时,会生成一个请求,并创建一个不再有你的下拉列表的新页面对象,因为它只被添加到button1处理程序中。

最简单的做法是将您的下拉列表正常添加到页面,但只需将Visible设置为false即可。然后,当他们点击按钮1时,将Visible设置为true。这将确保您的下拉列表始终存在。

动态控制很棘手,应尽可能避免,特别是如果您是ASP.Net的新手。

其实,我是能够使它工作..

我提前创建表创建的数据集,则:

tc = new TableCell(); 
    dd= new DropDownList(); 
    ddl.ID = dd1; 

    foreach (DataRow dr in dst.Tables[0].Rows) 
    { 
     ddl.Items.Add(new ListItem(dr["Text"].ToString(),dr["Value"].ToString())); 
    } 
    tcActions.Controls.Add(ddlActions); 

我不是一个专家或什么,我只是啄直到我让它做我想做的事。