Question

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 ?

Was it helpful?

Solution

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...

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
    }
}

OTHER TIPS

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

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.

Add controls in runtime and save on postback:

int NumberOfControls = 0;

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ViewState["b1"] = 0;
    }
    else
    {
        if ((int)ViewState["b1"] > 0)
        {
            CreateBtn();

        }
    }
}


protected void btn1_Click(object sender, EventArgs e)
{
    NumberOfControls = (int)ViewState["b1"];

    Button b1 = new Button();
   // b1.Attributes.Add("onclick", "x()");
    b1.Text = "test2";

    b1.ID = "b1_" + ++NumberOfControls;
    b1.Click +=new  System.EventHandler(btn11);
    Panel1.Controls.Add(b1);
    ViewState["b1"] = NumberOfControls;
}

protected void CreateBtn()
{
    for (int i = 0; i < (int)ViewState["b1"];i++)
    {
        Button b1 = new Button();
        // b1.Attributes.Add("onclick", "x()");
        b1.Text = "test2";
        b1.ID = "b1_" + i;
        b1.Click += new System.EventHandler(btn11);
        Panel1.Controls.Add(b1);
    }
}

protected void btn11(object sender, System.EventArgs e)
{
    Response.Redirect("AboutUs.aspx");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top