dynamic dropdownlist in asp.net

Jennie picture Jennie · Aug 19, 2009 · Viewed 10k times · Source

I created dropdownlist at runtime when a button is clicked.and i palced another button to get the selected text from dynamic dropdownlist.When i try to retrieve the selected text from dropdownlist it gives me the error called object reference not set, following is my code.

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;


    }

Answer

womp picture womp · Aug 19, 2009

You can't do it this way. Remember that on every request, you get a new page object, and new copies of all the controls in it. Any control you add dynamically must be added the same way every single time, otherwise it won't exist.

In this case, you add it once, when the button is clicked. When you click button2, a request is generated and a new page object is created that no longer has your dropdownlist, because it is only ever added in the button1 handler.

The easiest thing to do would be add your dropdownlist to the page normally but just set Visible to false. Then when they click button 1, set Visible to true. This will ensure that your dropdownlist will always be present.

Dynamic controls are tricky, and should be avoided when possible, especially if you're new to ASP.Net.