c# page level global object postback

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

Guest

How can you declare an object that is global to a page even on postbacks?

I currently have something like this

MyObject m;

throughout the page on the initial load everything works fine but on
postback anything referencing m I get NullReference.

How can I declare an object to have page level scope through postback.

Thanks
 
The easiest is to stick the value into ViewState:

ViewState["ValueIWishToKeep"] = value;

You can then pull it back out of ViewState, remembering to cast it out as
the type you wish it to be:

value = ViewState["ValueIWishToKeep"].ToString();

for example.

Remember that web apps are stateless. The other option is session, but this
makes it "global" to all pages.


---

Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

***************************
Think Outside the Box!
***************************
 
unless your app is on the local lan, you should avoid using ViewState and
increasing the payload. you should implement some sort of server based
session support. you can store the session key in viewstate.

-- bruce (sqlwork.com)


in message | The easiest is to stick the value into ViewState:
|
| ViewState["ValueIWishToKeep"] = value;
|
| You can then pull it back out of ViewState, remembering to cast it out as
| the type you wish it to be:
|
| value = ViewState["ValueIWishToKeep"].ToString();
|
| for example.
|
| Remember that web apps are stateless. The other option is session, but
this
| makes it "global" to all pages.
|
|
| ---
|
| Gregory A. Beamer
| MVP; MCP: +I, SE, SD, DBA
|
| ***************************
| Think Outside the Box!
| ***************************
|
| "Marty U." wrote:
|
| > How can you declare an object that is global to a page even on
postbacks?
| >
| > I currently have something like this
| >
| > MyObject m;
| >
| > throughout the page on the initial load everything works fine but on
| > postback anything referencing m I get NullReference.
| >
| > How can I declare an object to have page level scope through postback.
| >
| > Thanks
 
Hi.

If it's a light weight object and don't do much at initialization you can
declare it as a global variable in your Page's class and instantiate every
time page loads. But that would highly depend on particular situation.

Hope it helps,
Kikoz
 
Back
Top