.NET Daily

Failed to load ViewState. The control tree into which ViewState is being loaded must match the control tree…

Introduction

Darius

Darius

Darius Dumitrescu is a creative Senior CMS Consultant with in depth .NET knowledge, focused on Web Development and Architecture Design.


LATEST POSTS

How to Deliver Accurate Project Status Reports 21st April, 2018

JIRA Workflow for Web Development Example: Simple and Effective 17th April, 2018

Common .NET Exceptions

Failed to load ViewState. The control tree into which ViewState is being loaded must match the control tree…

Posted on .

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.System.Web.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.

Scenario 1: You try to dynamically add controls to a ContentPlaceholder or Panel then you click a button or make a PostBack somewhere and then you see the BIG error.

Cause of  Scenario 1: When you make the PostBack on the server, somehow you manage to change the IDs of the controls in the container. Because the first time the controls were saved in the Viewstate, any change on the ID names on postback may trigger the error.

Resolution for Scenario 1: Pay attention to the foreach statement where you add controls and make sure every time you add the controls to the container you  have the same IDs.

Let me give you an example. Let’s say I have a group of three TextBoxes for Firstname, Lastname and Address.

If at the page load I generate two groups of controls:

txtFirstnameIndex0;

txtLastNameIndex0;

txtAddressIndex0;

and

txtFirstnameIndex1;

txtLastNameIndex1;

txtAddressIndex1;

And when I click Add button for adding another group of controls and then I generate the following group of controls:

txtFirstnameIndex1;

txtLastNameIndex1;

txtAddressIndex1;

and

txtFirstnameIndex2;

txtLastNameIndex2;

txtAddressIndex2;

and

txtFirstnameIndex3;

txtLastNameIndex3;

txtAddressIndex3;

Then at the page load I will see the BIG error because in the ViewState I already have the group of controls starting from Index 0 and not Index 1.

Darius

Darius

Darius Dumitrescu is a creative Senior CMS Consultant with in depth .NET knowledge, focused on Web Development and Architecture Design.

There are no comments.

View Comments (0) ...
Navigation

Privacy Preference Center