asp.netdynamiccontrolspersistenceloadcontrol

Dynamically Loading Controls and Persistence in ASP.NET


I am loading a series of controls in the Page_Load event. However, I have to recreate those controls each page load, which means storing their data elsewhere. This is cumbersome.

protected void Page_Load(object sender, EventArgs e)
{
   MyControl control = (MyControl)LoadControl(...);
   control.Initialize(GlobalClass.controlData);
   //^gives the control the data it had previously.  
   //Or use ViewState["controlData"] if serializable.
   Controls.Add(control);
}

I feel like I should be using if (!IsPostBack) {}, but I don't know how, or why.

In contrast, if I place the controls into the markup, then the controls seem to stay persistent. For example, a button in mark-up will remember any changes to its Text property (I think?).

<asp:Button ID="buttonText" runat="server" 
            Text="Text Segment" onclick="buttonText_Click" />

How do I maintain some sort of persistence with dynamically added controls, like controls added via mark-up? This would save me much work and frustration.

Thanks.

(I've coded for a small eternity, but the more I do ASP.NET, the more confused I become. Which is exactly the opposite of what how I understood learning to work :-P.)


Solution

  • For dynamically loaded controls, if you load them during the Page_Init event, you can then add them to the ViewState and they will be able to retain state from PostBack to PostBack.