views:

144

answers:

3

Hi; I Add Control Dynamiclly but; easc Postback event my controls are gone. I Can not see again my controls.

So How can I add control ?

+1  A: 

Because you must recreate your controls on every postback, see this article

Shammy
Ok, bu Can I Keep in ViewState blog? I want When I add a Control, which must be there each postback. If I recreate all control, I will lost control's information and other info typed by users ( like Textbox in a control ).So What is the solution?
atromgame
A: 

You should always assign a unique ID to the UserControl in its ID property after control is loaded. And you should always recreate UserControl on postback.

To preserve posback data (i.e. TextBox'es) you must load UserControl in overriden LoadViewState method after calling base.LoadViewState - before postback data are handled.

Tadas
Ok, but Can I Keep in ViewState blog? I want When I add a Control, which must be there each postback. If I recreate all control, I will lost control's information and other info typed by users ( like Textbox in a control ). So What is the solution?
atromgame
I've updated my answer.
Tadas
A: 

Add the controls in the Page's Init event and they will be preserved in viewstate when posting back. Make sure they have a unique ID.

See this link...

http://stackoverflow.com/questions/877339/asp-net-add-control-on-postback

A very trivial example..

public partial class MyPage : Page
{
    TextBox tb;

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        tb = new TextBox();
        tb.ID = "testtb";
        Page.Form.Controls.Add(tb);
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        //tb.Text will have whatever text the user entered upon postback
    }
}
George