开发者

Dynamically Loading Controls and Persistence in ASP.NET

开发者 https://www.devze.com 2023-01-14 05:32 出处:网络
I am loading a series of controls开发者_Python百科 in the Page_Load event.However, I have to recreate those controls each page load, which means storing their data elsewhere.This is cumbersome.

I am loading a series of controls开发者_Python百科 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.)


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.


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:

Accessing controls created dynamically (c#)

0

精彩评论

暂无评论...
验证码 换一张
取 消