views:

74

answers:

2

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?

A: 

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.

Glennular
A: 

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.

Tejs
That's exactly what I'm doing, and I believe that's what's causing the problem: control Y is added before the viewstate is restored, but control X is not, bacause it is no longer needed.However, the viewstate tries to restore control X's state , but it doens't find that control
Emil D
Hrm, that's a tough question then. It would be hard to speculate without seeing the full code and trying to run some test runs tinkering with the life cycle. Have you tried just leaving X in and then removing it after the view state is restored?
Tejs
Well, I guess that's what I'll end up doing, but it's an ugly solution: you can't just leave a dynamic control in there, since it has to be reloaded at every postback.I'd essentially be loading a new control , just to remove it right afterwards:S
Emil D