I am facing a Viewstate load issue with my page.
Page has a login facility to log in admin and non-admin users. A strange behavior occurs when a non-admin user logs in to the page and clicks a checkbox which has autopostback enabled. (error details are given below)
Later I found that, in the navigation panel on the left side (which hosts links)
Sidebar is something as depicted below
Security
---------
Link1
Link2
Link3
Configuration
---------
Link1
Link2
If anything more than appears under the "Configuration" section, this exception gets thrown. The links are dynamically removed (from a full list) based on the user's privilege on Page_Load.
How can I trace this kind of issues? I enabled all the exceptions in Visual Studio but it's not breaking to see which control causes this issue?
Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.
[HttpException (0x80004005): Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.]
System.Web.UI.Control.LoadViewStateRecursive(Object savedState) +380
System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) +144
System.Web.UI.Control.LoadViewStateRecursive(Object savedState) +214
System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) +144
System.Web.UI.Control.LoadViewStateRecursive(Object savedState) +214
System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) +144
System.Web.UI.Control.LoadViewStateRecursive(Object savedState) +214
System.Web.UI.Page.LoadAllState() +464
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1729
If you look at the page cycle in this article you can see that the viewstate is loaded before page load and saved before render. You are removing the controls in page load which is after the load of viewstate, which means that on postback there is less data in viewstate than the page is expecting. Try removing the controls in prerender which should happen after the saving of viewstate and this should solve your problem.
James :-)