tags:

views:

425

answers:

6

I am having a problem in which two controls which are added programmatically are trying to load each other viewstate, I want to clear the viewstate before loading the controls, I tried Viewstate.Clear but it did nothing, when I disable viewstate on the container of my controls everything works fine except that the control's state is not kept. Is there a way to clear viewstate of just a specific control?

A: 

Assuming both controls inherit from System.Web.UI.Control. You can disable their individual ViewStates by setting their EnableViewState to false. Also you can clear their ViewState, as each control has a ViewState property.

Yuriy Faktorovich
The problem is he'd have to do it by overloading the Page's Render method as ViewState is saved in the page lifecycle right before Render is called by the SaveViewState event. Any other event would result in it being there still.
Nissan Fan
@Nisssan: You mean if he clears the ViewState property as opposed to disabling ViewState?
Yuriy Faktorovich
Yes. If he disables it that's fine ... no need to clear. But if he just wants to clear it out he'll have to do it in the Render event. Otherwise, he'll clear it ... but the even before Render is SaveViewState ... so it'll add it in.
Nissan Fan
A: 

Make sure the id's of the two programmatically added controls are different and the ViewState problem should go away.

Jeff Siver
A: 

You can disable viewstate on a specific control:

EnableViewState="False"
Luhmann
+3  A: 

From your description, it would seem that you are making one of the common mistakes when loading your dynamic controls - either you are loading them too late or you are not assigning them unique IDs (and assigning them the same unique id each time a postback occurs).

If this is indeed your problem, then clearing the viewstate is not the appropriate action to be taking. It is quite simple to fix, check these three links:

http://msdn.microsoft.com/en-us/library/ms972976.aspx

http://www.4guysfromrolla.com/articles/092904-1.aspx

http://geekswithblogs.net/shahed/archive/2008/06/26/123391.aspx

slugster
As an addon: Make sure to create your controls as early as possible and not ever after `Page_Load`. `Page_Init` is preferred, but the `Page_Load` event will work. `Page_PreRender` will **not**
Earlz
A: 

Yes.

string controlName = "name of control";

ViewState[controlName] = null;

// create control, add it to the page

...

cpkilekofp
A: 

If ViewState gets in your way and you haven't done so already, please read

TRULY understanding ViewSate

It will make you much more comfortable in working with ViewState and the whole ASP.NET page lifecycle.

Rune