views:

39

answers:

2

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

+1  A: 

I understand your point. Yes, this is cumbersome, but that's how a stateless technology works.

There's no way of achieving the same bahaviour of static controls (the ones that you put in the HTML markup).

Follow the tips I gave in this answer:

http://stackoverflow.com/questions/2982198/accessing-controls-created-dynamically-c/2982271#2982271

Leniel Macaferi
A: 

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.

Joel Etherton
You don't mean add the control itself, you mean add the various properties of the control, correct? I already tried adding the control itself (faster than adding all necessary properties :-P), and controls are not serializable.
Yerg
@Yerg - If memory serves (and I haven't looked it up to verify it), just by setting `EnableViewState = true;` on the control in Page_Init queues it up to be in the ViewState. You don't need to add anything manually.
Joel Etherton
I have Reflectored the Text Box control, and it always saves things in the ViewState from what I recall. I'm curious what EnableViewState really does... Either way, the only way to save a list of dynamically added controls is to split the control from its data, and based on how many instances of the data, on page load make that many instances of the control with that data. Any other ideas?
Yerg