"Cannot load ViewState" after dynamic control changed

1.2k Views Asked by At

In my ASP.NET page I have to dynamically choose and load a custom control, depending on the selected value in a dropdownlist.However I encountered the following problem: When the parameters of the dynamically loaded control are changed, and then the selection in the dropdownlist is changed( thus forcing me to load a different dynamic control the next time the page reloads ), I end up with a "Cannot load ViewState" exception.I assume that this happens because the ViewState is trying to restore the parameters of the old control and it doesn't find it. So , is there any way to stop the viewstate from attempting to restore the state of the non-existig control?

4

There are 4 best solutions below

1
On

Had the same issue where a variable length list of controls was added, rearranged and/or modified by the user and is changable during each postback.

The answer is surprisingly simple.

When you create the dynamic control set "EnableViewState = False" before you add it to the pages control collection. Then no viewstate information is stored and regardless of how many dynamic controls are added or removed or re-ordered the viewstate for everything else will work correctly.

If your adding these dynamically you are normally setting all the properties anyways so it didn't actually create any work in my case which is very similar.

0
On

I've the same issue with grid control. I was binding dataviews dynamically and according to DarrenMB's solution I've just write EnableViewState = false; and problem solved.

Infragistics.Web.UI.DataSourceControls.DataView dvMesaj = new Infragistics.Web.UI.DataSourceControls.DataView();


        whdsShowMessages.DataRelations.Clear();
        whdsShowMessages.DataViews.Clear();
        whgridShowMessages.Rows.Clear();
        EnableViewState = false; //here is the solution..
        whdsShowMessages.DataViews.Add(dvKisi);
        whdsShowMessages.DataViews.Add(dvMesaj);
0
On

You should load the controls the exact same way initially and then alter then after LoadViewState or disable the viewstate on the dynamic controls you know will not be in sync with the page.

3
On

It sounds like the state of the drop down / added control is not being restored before you are restoring the view state. If you have the drop down defaulted to show control X, and the user changes it to show control Y, the page must add control Y to the control collection before view state is restored.