Failed to load viewstate ? Typical problem, with an obvious solution.

Understanding viewstate is fundamental in asp.net, especially if you had run into :

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.

The only way to resolve is a proper understanding of viewstate.

http://geekswithblogs.net/FrostRed/archive/2007/02/17/106547.aspx is a interesting post on viewstate that i happen to read today, pointed out to me by someone who ran into a viewstate problem about the control tree not matching and was clearly afraid of adding controls dynamically after reading some facts presented in that article. Who wouldn't :-)

While the post gives us a very good understanding of viewstate and how it can fail, so i encourage you to read it first, might seem lengthy but I assure  you, it's quite interesting. However, when you're done, follow my rant here, since I feel it's important to know, that, the failure can only happen when either done deliberately as per the sample code in the post i linked to above or to *not* understanding viewstate and how it works.

So how can we easily avoid these failures ? Let's look at his first code example, and build onto that :

protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
Button btnClickMe
= new Button();
form1.Controls.Add(btnClickMe);
btnClickMe.Text
= "Click me";
}
else
{
Label label
= new Label();
form1.Controls.Add(label);
}
}

As you can note above, this is problematic, since the control into which viewstate is restored is matched by control index, so when the index changes, as is clear in the above code, because if btnClickMe was loaded in for example index [0], now upon postback, after the page has been recreated and rebuilt, the Label "label" is loaded in index [0] instead and takes the place of the button. So this means viewstate that was meant for the button is loaded into the label instead, and the output in the screen after clicking the button is "click me" which was clearly not provided to the label's text property.

Now that we understand the problem, how can this sample apply in real world or why would anybody want to do something like this ? Basically in short, why is viewstate being utilized, if it's not needed after postback ? Button btnClickMe is not reloaded after postback, so it's safe to turn off viewstate on this control, and problem is solved.

This is a typical situation where you deliberately want viewstate to fail, apart from that i see no real use to want to maintain viewstate, which is also bloat on a control that clearly is not utilizing it.

so a rewrite ? here :

protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
Button btnClickMe
= new Button();
// note the addition of the following line
btnClickMe.EnableViewState = false;
form1.Controls.Add(btnClickMe);
btnClickMe.Text
= "Click me";
}
else
{
Label label
= new Label();
form1.Controls.Add(label);
}
}

Otherwise, again as per the sample code above, had we been using viewstate, then the problem would resolve itself, if we recreated the control also after postback, which is one of the basic rules of dynamic controls creation. I say rules but really it's the logical thing to do since the page is destroyed after postback and asp.net will have no recollection of controls you added dynamically since memory is cleared, so it's upto you to build it up again manually :-)

protected void Page_Init(object sender, EventArgs e)
{
// button will be created even after postback
Button btnClickMe = new Button();
btnClickMe.EnableViewState
= false;
form1.Controls.Add(btnClickMe);
btnClickMe.Text
= "Click me";
if (IsPostBack)
{
Label label
= new Label();
form1.Controls.Add(label);
}
}

So, bottom line, a proper understanding of viewstate, knowledge of the page life cycle, so you know in what phase it's safe to build your control, which will guarantee that viewstate is reloaded into the control(so you load it prior to page_load), and you got it right. For a proper understanding of the page life cycle, you can read the following document on msdn : http://msdn2.microsoft.com/en-us/library/ms178472.aspx?wt.slv=ColumnA

Update Jan/04/2008: I forgot to mention a gotcha, so here it is :  

Another gotcha you want to avoid is also the order of controls, that is, when you're loading a dynamic control, make sure the order in which you create it, has the same order when you recreate it. Confused, here let me explain better :

protected void Page_Init(object sender, EventArgs e)
{
if (IsPostBack)
{
Label label
= new Label();
label.ID
= "label1";
form1.Controls.Add(label);
label.Text
= "label";

Button btnClickMe
= new Button();
btnClickMe.ID
= "button1";
form1.Controls.Add(btnClickMe);
btnClickMe.Text
= "Click me";

}
else if (!IsPostBack)
{
//Now lets change the order
//during postback and we are
//recreating the controls
Button btnClickMe = new Button();
btnClickMe.ID
= "button1";
form1.Controls.Add(btnClickMe);
btnClickMe.Text
= "Click me";

Label label
= new Label();
label.ID
= "label1";
form1.Controls.Add(label);
label.Text
= "label";
}
}

As you can note above, the order in which controls are added changes after postback. In this scenario what really happens ? The viewstate meant for the button is loaded into the label and the viewstate meant for the label is loaded into the button. So, you really want to be careful with the order in which you recreate your controls.

Published Friday, January 04, 2008 9:51 AM by alessandro
Filed under: ,

Comments

# re: Failed to load viewstate ? Typical problem, with an obvious solution.

Friday, January 04, 2008 11:26 AM by efdee

I ran into similar problems little over a year back. Would have been nice to have this blog post back then ;)

# Failed to load viewstate ? Typical problem, with an obvious solution.

Thursday, January 10, 2008 5:28 PM by DotNetKicks.com

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# re: Failed to load viewstate ? Typical problem, with an obvious solution.

Saturday, January 12, 2008 1:07 AM by Wayne Hawkins

I am getting this error my self. I know for a FACT, that it is not my code. My computer crash and I had to pull the power lead and restart it. After a restart, I am getting this error. So it has to be something to do with Visual Stuiod or IIS system. So boo for Microsoft, this is a fault at there end. I think the solution at this point is start a new project in Visual Stuiod and then move my files over. I bet it will then work.

# re: Failed to load viewstate ? Typical problem, with an obvious solution.

Sunday, February 10, 2008 5:27 PM by Erik

Nice topic, i can follow.

But what about AJAX - update panel...

I got the error, no dynamic control loading (on my part).. Its a update panel with a multiview. could it be that the update panel couses a reordering or when the page is loading asp.net "thinks" there are less controls then after the postback (async...)

:-)

# re: Failed to load viewstate ? Typical problem, with an obvious solution.

Tuesday, February 19, 2008 4:26 PM by Flavio Spagnuolo

Also happens that if you save something in the viewstate before the statebag has been saved but also before your control has been added to the parent´s control collection, it may occur that your values would not be restored after postback. Is happened to me. My solution was to set the viewstate properties after the control was added to the parent´s control collection.

# re: Failed to load viewstate ? Typical problem, with an obvious solution.

Friday, February 29, 2008 8:16 PM by Jay w

This has helped me greatly, as I am using user controls to dynamically generate forms.  Disabling the viewstate allowed me to not have to reload the controls during onit (which is good if you want to keep viewstate, but in my case I recreate it anyways)

# re: Failed to load viewstate ? Typical problem, with an obvious solution.

Thursday, July 10, 2008 4:32 PM by Henry R

Excellent article, very useful. Thanks a lot.

# re: Failed to load viewstate ? Typical problem, with an obvious solution.

Thursday, July 31, 2008 9:33 AM by L.Holota

nice, helped at the right moment :)

# re: Failed to load viewstate ? Typical problem, with an obvious solution.

Wednesday, September 17, 2008 11:46 AM by Sephiroth

Nice solution. Just the wrong example though. I believe you were looking for the Button and the DropDownList as an example of a ViewState error.

# re: Failed to load viewstate ? Typical problem, with an obvious solution.

Wednesday, October 29, 2008 5:28 AM by ivan

I'm a newbie to web programming, thanks for this post I nearly went into programming how to by pass the viewstate  problem - after reading first few sentences I't became clear I dont actually need viewstate enabled on user controls that I added dynamically.Thanks a bunch!

# re: Failed to load viewstate ? Typical problem, with an obvious solution.

Thursday, November 20, 2008 11:48 AM by Brian Thomas

What are you suppose to do when you receive this error and you haven't added any dynamic controls?

I have a datalist and in the edit template I have an fckEditor. When I select edit I receive this error. It only works when I remove the editor. I have a similar setup in another web page with no problems.

I don't know if this means anything but I have to select edit twice before it goes into edit mode.

Any ideas? Thank you.

# re: Failed to load viewstate ? Typical problem, with an obvious solution.

Wednesday, December 10, 2008 2:15 PM by Beska Miltar

We're running into this problem and have been for some time.  I spent some time looking at the pages that we were seeing this error on, looking for where controls might be added or removed.  Nothing like that is happening on the page anywhere.  Then, after further investigation, we discovered that clearing "temporary internet files" on the client would fix the problem.

It looks like the problem can also be tickled by the user having a version of the page cached that doesn't match up exactly with the current version of the page.  This is probably happening for us because some items were removed from the viewstate during a release (not removed from the page...just had EnableViewState set to false.)

Now we just have to figure out what to do about it...

# re: Failed to load viewstate ? Typical problem, with an obvious solution.

Tuesday, January 27, 2009 9:26 PM by Merly

Thanks! Setting the EnableViewState = false of the control helps.

# .NET | Failed to load viewstate? « DYERPROJECTS

Tuesday, February 10, 2009 10:50 PM by .NET | Failed to load viewstate? « DYERPROJECTS

Pingback from  .NET | Failed to load viewstate? « DYERPROJECTS

# .NET | Failed to load viewstate? « DYERPROJECTS

Tuesday, February 10, 2009 11:01 PM by .NET | Failed to load viewstate? « DYERPROJECTS

Pingback from  .NET | Failed to load viewstate? « DYERPROJECTS

# re: Failed to load viewstate ? Typical problem, with an obvious solution.

Monday, February 16, 2009 5:13 AM by easanka

the artical was really help full in my case.. i got the same error when i press a button in update pannel.thing is i dont have any dynamic controls adding on my page. anyhow by adding the "EnableViewState= fals;" on Page_Load ()my problem was solved.. thank you for everyone..

# re: Failed to load viewstate ? Typical problem, with an obvious solution.

Sunday, May 31, 2009 2:48 AM by Mohammad Insairar

Great Article, thanks alot,

but what about loading usercontrols dynamically, i had this problem and i couldn't just disable the view state for the loaded controls.

I had to redirect to the same page again just before loading a new usercontrol, to clear the viewstate from the old control's values.

# re: Failed to load viewstate ? Typical problem, with an obvious solution.

Wednesday, August 05, 2009 8:39 AM by Peter

I'm also having this issue without any dynamic controls on the page. Indeed, if I stop any code from firing on postback I still get the problem. Debugging indicates that although the page is not refreshing, the pageload for each control on the page is still firing.

Any ideas?

# SharePoint Webpart dyn. Controls ViewState Error. « PANVEGA’s Blog

Pingback from  SharePoint Webpart dyn. Controls ViewState Error. « PANVEGA’s Blog

# re: Failed to load viewstate ? Typical problem, with an obvious solution.

Thursday, October 29, 2009 5:21 PM by Ron Bars

I am glad it answered my question. Enableviewstate is the Answer!

Leave a Comment

(required) 
(required) 
(optional)
(required)