ASP.NET: Viewstate and programmatically adding user controls?

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.

Up vote 4 down vote favorite 1 share g+ share fb share tw.

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 asp.net usercontrols link|improve this question asked Nov 4 '09 at 15:19burnt1ce1,65921647 50% accept rate.

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: msdn.microsoft.com/en-us/library/ms17847... 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.

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 4 '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 4 '09 at 17:45 Thank you very much. Your suggestion saved me. =) – burnt1ce Nov 5 '09 at 14:51.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions