There was an error in this gadget

Search This Blog

Thursday, December 22, 2011

Failed To Load Viewstate

Once I encountered the following error

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


I searched a lot on google and finally i found one solution.

Here is the reason why the error happens:

If a control is added dynamically to a placeholder say (UserControl1.ascx) and the control's viewstate is enabled ,thenafter on the next postback a different control is added say (UserControl2.ascx) to the placeholder.

when asp.net try to load the viewstate of the control contained at the placeholder it's expecting the previous control  u added :(UserControl1.ascx) but it will encounter another control instead  (UserControl2.ascx) in the place of the first control SO IT WILL FAIL.

Viewstate of the control tree in the placeholder child controls is saved by index not by key so even if we give our ascx control as a key before adding it to the placeholder we will get the same error.


Solution:

Just disable viewstate of the usercontrol.


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind=" abc.aspx.cs" Inherits="#####"  EnableViewState="false"%>

20% OFF + FREE Set-up on select items! Online Exclusive for New Customers Only.