8

When programmatically adding user controls using LoadControl(string path), when, in the user control's page life cycle, does it initialize its sub-controls with its viewstate?

I'm asking this question because one of my user controls that's being programmatically loaded has a TextBox control that is not being initialized/loaded by it's viewstate on PostBack on the Page_Load event (which is not the case for a regular .aspx pages and hence my confusion). Overall, I need to retrieve values from the Textbox control.

Thanks

burnt1ce
  • 14,387
  • 33
  • 102
  • 162
  • Does this answer your question? [Event won't fire to dynamically added control](https://stackoverflow.com/questions/56281364/event-wont-fire-to-dynamically-added-control) – Peter O. May 11 '20 at 00:41

1 Answers1

11

ViewState is loaded before the Page_Load event. If you want your control to work with ViewState, you need to load it and add it to the page before that event — usually on PreInit.

The life cycle reference is here:
http://msdn.microsoft.com/en-us/library/ms178472.aspx?ppud=4

Read the description for the Pre Load event, which immediately precedes Page Load:

Use this event if you need to perform processing on your page or control before the Load event.

Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

Thus by Pre Load time it's already too late. Also, the description for the PreInit event specifically mentions that it's the place to "create or re-create dynamic controls."

Community
  • 1
  • 1
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • Thanks! On a related note, the user control that I'm adding programmatically happens in another user control that is being loaded declaratively. This declared parent user-control's PreInit event doesn't get fired (so the method 'protected void Page_PreInit(object sender, EventArgs e)' doesn't get called). Do you know why Page_PreInit doesn't get called in this declared user-control? – burnt1ce Nov 04 '09 at 17:37
  • Controls themselves don't have a pre-init, because the control page lifecycle events are called from the page and at the PreInit point the controls aren't all ready yet. Use Init instead. – Joel Coehoorn Nov 04 '09 at 17:45