Skip to main content
 首页 » 编程设计

c#之asp.net 中的动态下拉列表

2024年02月24日18itcoder

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

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 的新手。