Jeevan Bhatt
Jeevan Bhatt

Reputation: 6101

On postback htmlgeneric control remove its childeren controls in asp.net, why?

I have an htmlgeneric control and on run time i am adding control in it but when i click on any button then added controls disappear.

Upvotes: 0

Views: 283

Answers (1)

djdd87
djdd87

Reputation: 68506

Dynamically created controls need to be created on every post back. You also need to give them an ID if you want to maintain and restore their ViewState.

For example, this will show the TextBox the first time the page is loaded, but on any subsiquent page loads, the control will be missing:

protected void Page_Init(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        TextBox newControl = new TextBox()
        {
            ID = "newControl"
        };
        SomeControl.Controls.Add(newControl);
    }
}

However, if you create the control on every postback with the same Id, then the control will be maintained with it's Text:

protected void Page_Init(object sender, EventArgs e)
{
    TextBox newControl = new TextBox()
    {
        ID = "newControl"
    };
    SomeControl.Controls.Add(newControl);
}

Here's a good article about dealing with dynamic controls.

Upvotes: 1

Related Questions