Tuesday, July 17, 2012

Controls dynamically added in ASP.NET are lost after a postback

If you are loosing your controls added dynamically to a web page after a full or partial postback, is because you are not creating them in the Page.Init.

According to the ASP.NET Page Life Cycle, PostData (all values inputed on the client side) is applied between the Page.Init and Page.Load, so, if you add a control in the Page.Init, they will not lose their state and you don't have to recreate them.



        protected void Page_Init()
        {

        Control ct = ParseControl("");

        Page.Controls.add(ct);

        }


TemplateControl.ParseControl the easy way to add controls

The TemplateControl.ParseControl() is a powerfull tool to convert a string into a control, if you want to add controls to your web page this object will help you avoid a lot of coding.





// Create the label control
Control ct = ParseControl("");

// Add the control to the page
Page.Controls.Add(ct);

//
// Create a string with a table and a label
string tbl = "b
Text
"; // Create the control Control ctrl = Page.ParseControl(tbl); // Add it to the page PageControls.Add(ctrl);