Accessing ViewState in User Control

J

Jordan

My ASP.NET 1.1. app dynamically loads a user control into a PlaceHolder
control that exists in an aspx page. The user control is loaded during the
Page_Load event of the aspx. The PlaceHolder's EnableViewState property
value is "true".

In the user control's Page_Load event procedure I want to read/write to the
ViewState.

Writing to the ViewState, like this, seems to be no problem:
this.ViewState["MyKey"] = someValue;

But attempting to read the value back from the ViewState causes an exception
to be thrown: "Object reference not set to an instance of an object"
someValue = this.ViewState["MyKey"].ToString();

I threw this.TrackViewState(); in the user control's Page_Load event
procedure to see if that was required, but apparently no dice.

What must I do to be able to use ViewState of the user control? Note that I
don't really care if I'm using the ViewState of the user control or of the
page that hosts the user control (I just don't want to store the value in
the Session).

Thanks!
 
C

Cathal Connolly [VB MVP]

You can't access the viewstate once your control starts to render, as it
will render the new viewstate. You can read the value back at any stage
before that, the PreRender event is a good place to do this.

Cathal
 
C

Chris Botha

I'm using it, no problem, but with a difference. I have a panel on the page
and dropped the control into the panel in design view of the page (for
positioning) instead of dynamically loading it into a PlaceHolder.
 
J

jhcorey

I've done this just like you describe.
In my case I found that for dynamically loaded controls I had to load
them every time the page loaded, and set the ID property of the control
to the same (arbitrary) value every time so that things stayed in sync.

So in VB I had
PlaceHolder.Controls.Clear()
PlaceHolder.Controls.Add(myControl)
myControl.ID = "abc"

I think that with multiple controls the last line is needed to keep
viewstate in sync with individual controls.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,778
Messages
2,569,605
Members
45,237
Latest member
AvivMNS

Latest Threads

Top