Loading dynamic user controls from Page_Load cause ViewState problems.

I've seen couple of post on that issue lately so I decide to comment on that Issue. ViewState holds controls state as they where before server side processing of page finished. Controls state is saved by SavePageStateToPersistenceMedium to hidden field and retrieves from hidden field by LoadPageStateFromPersistenceMedium.

As I post in my article about ViewState viewer (http://www.codeproject.com/aspnet/viewstate_viewer.asp) viewstste is order by the controls position in controls collection of HtmlForm object. If controls add to HtmlForm after LoadPageStateFromPersistenceMedium load controls viewstate there isn't any correlation between controls order and viewstate order and … you probably got a problem.

If you will follow events order on page you will see that Page_Load (event) happened after LoadPageStateFromPersistenceMedium. Page init happen just before LoadPageStateFromPersistenceMedium. So moving your code (that loads user control) from Page Load event to Page init event will cause control tree to be finish before ViewState load and viewstate behave as expected.

2 Comments

  • VS2005, when I add my user control dynamically at page init event, I am still missing the viewstate after the 1st post back. Subsequent postbacks, it does accurately preserve the values as I've changed them in the user control. I can not figure out what is different from the 1st postback??

  • Moving the load control the page load event solved my problem. I found this in the URL above. Not sure why every site I visit says to use the page init event.

Comments have been disabled for this content.