1

单击按钮时,我在运行时创建了下拉列表。然后我放置了另一个按钮以从动态下拉列表中获取选定的文本。当我尝试从下拉列表中检索选定的文本时,它给了我一个名为未设置对象引用的错误,以下是我的代码.

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;


    }
4

2 回答 2

4

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

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

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

动态控件很棘手,应尽可能避免,尤其是当您是 ASP.Net 新手时。

于 2009-08-19T06:50:28.130 回答
0

实际上,我能够使它工作..

我在创建表之前创建了一个数据集,然后:

   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);

我不是专家或任何东西,我只是啄它,直到我让它做我想做的事情。

于 2013-03-08T18:59:06.463 回答