Tuesday, May 10, 2011

How to retain all of the dynamically added asp controls


The asp.net doesn't keep control state.
So if you want to create control dynamically, you should create the dynamic control every time in Page_Load function.
You can store the dynamic control into cache, and then read it at page_load function.
Here is a example, maybe help you.
    protected void Button4_Click(object sender, EventArgs e)
    {
        Panel tt = new Panel();
        TextBox tb = new TextBox();
        tb.ID = "txtName";
        tb.Text = "hello";
        tt.Controls.Add(tb);
        PlaceHolder2.Controls.Add(tt);
        Cache["tt"] = tt;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Cache["tt"]!=null)
        {
            Panel tt = Cache["tt"] as Panel;
            PlaceHolder2.Controls.Add(tt);
        }
    }


No comments: