views:

1081

answers:

3

I have an aspx page which is loading some controls dynamically on postback (ie when a click event happens) and adding them to a placeholder. Depending on what is clicked a different set of controls needs to be loaded.
This works perfectly the first time, but when I clear the placeholder's controls and attempt to dynamically load a different set of controls I get 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."

This happens even if I do ViewState.Clear().

Is there a way to do this?

A: 

When dynamically creating controls you must ensure that every control you create has an unique id.

I think what is happening here is that you are naming your controls like: Control1, Control2, Control3.

And perhaps when you click to create a different set of controls you might give the same name to a different type of object, lets say Control1 was first created like a Textbox and when you click its a checkbox.

Without seeing the code is tough to tell why ViewState.Clear() is not working, but if you are trying to clear the viewstate you don't need a postback, you can try requesting a new page and pass the arguments on the querystring instead of a postback. This will be faster too as you don't have to send the ViewState information back to the server.

Sergio
+4  A: 

Yuriy Solodkyy explains it well here: Dynamically Created Controls in ASP.NET

Timothy Khouri
A: 

Thank you. Yuriy's article was a great help.

Barry