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

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.