1

the code written below displays the text box for a certain condition.But when i click another unrelated button or link it dissapears.i need it to stay visible when i do other activities on the webpage

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    TextBox new_textbox = new TextBox();

    if (DropDownList1.Text.Equals("OFF"))
    {
        new_textbox.ID = "txt" + 1;

        PlaceHolder1.Controls.Add(new_textbox);
        Label5.Visible = true;
        new_textbox.Visible = true;
    }
    else
    {   
        Label5.Visible = false;
    }        
}
Seth Flowers
  • 8,990
  • 2
  • 29
  • 42
Huga
  • 571
  • 1
  • 8
  • 21

1 Answers1

1

This question has been asked on SO before: Dynamically added controls in Asp.Net

You are only adding this control in a certain situation, specifically when DropDownList1.Text.Equals("OFF"). Could you instead have a static control that you just set visible in this case?

According to msdn's Add Controls to an ASP.NET Web Page Programmatically:

Controls are typically added to the page during the page's initialization stage. For details about page stages, see ASP.NET Page Life Cycle Overview.

The quote links to ASP.NET Page Life Cycle Overview.

You have to be careful about adding controls dynamically, see this msdn page about Dynamic Web Server Controls and View State.

Community
  • 1
  • 1
Seth Flowers
  • 8,990
  • 2
  • 29
  • 42