page viewstate

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

How come I can use the following line in my page_load
ViewState["abc123"] = "xxxx"

But when I try the same line of code in another function I get the following compile error
An object reference is required for the nonstatic field, method, or property 'System.Web.UI.Control.ViewState

Do I need to reference ViewState some how thru the HttpContext.current ???
 
When you access it through Page_Load it is intrinsically available. Can you
send an example of the code where ViewState is not available?

jzink said:
How come I can use the following line in my page_load:
ViewState["abc123"] = "xxxx";

But when I try the same line of code in another function I get the following compile error:
An object reference is required for the nonstatic field, method, or
property 'System.Web.UI.Control.ViewState'
 
Do you mean another function or another class? The Page class inherits
System.Web.UI.Control. The ViewState property is a property of the base
class, so in any class that inherits System.Web.UI.Control has a ViewState
property. If you're referring to a method in a non-Control class, such as a
Class Library, you would have to get the ViewState from the
System.Web.HttpContext.Current.Handler class. This class is an iHttpHandler
class, so you would need to cast it as a System.Web.UI.Page class. Example:

((System.Web.UI.Page)
System.Web.HttpContext.Current.Handler).ViewState["abc123"] = "xxxx";

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.

jzink said:
How come I can use the following line in my page_load:
ViewState["abc123"] = "xxxx";

But when I try the same line of code in another function I get the following compile error:
An object reference is required for the nonstatic field, method, or
property 'System.Web.UI.Control.ViewState'
 
I was hoping to do exactly as you describe (i.e., access the ViewState
from a class), however, when I implement the code you suggest, I get the
following compile-time error:

'System.Web.UI.Control.ViewState' is
inaccessible due to its protection level

Could you kindly provide an explanation for how to get around that? Many
thanks in advance.
 
Back
Top