variable scope and persistence

C

Cole Trickle

Hello...
I assign a variable from the querystring to a class level private variable
as follows

public class CrsInstnc : System.Web.UI.Page {
private string tcoRef = "";

private void Page_Load(object sender, System.EventArgs e) {
if(!IsPostBack){
if(Request.QueryString["ref"] != null){
this.tcoRef = Request.QueryString["ref"].ToString();
}
...
}
}

Every time the page posts back to itself the variable this.tcoRef is empty.
Am I doing something wrong? When the page posts back to itself does the
whole class start from scratch? Should I store the information elsewhere?
Thanks
 
E

Eliyahu Goldin

Every time the page posts back to itself the variable this.tcoRef is
empty.
Am I doing something wrong? When the page posts back to itself does the
whole class start from scratch?
Exactly, this is how web applications work.
Should I store the information elsewhere?
Yes, in a session variable.

Eliyahu
 
?

=?ISO-8859-1?Q?=22Anders_Nor=E5s_=5BMCAD=5D=22?=

Cole said:
Every time the page posts back to itself the variable this.tcoRef is empty.
Am I doing something wrong? When the page posts back to itself does the
whole class start from scratch? Should I store the information elsewhere?
The class is not persisted between postbacks. You must store the value
in either the session state or in the page's view state to persist it
between postbacks.

To stor a value in and retrieve it from the session state do this (C#):
if (Page.IsPostBack) {
// Read from session state
myString=(string) Session["MyValue"];
} else {
// Store in session state
Session["MyValue"] = myString;
}

To store a value in and retrieve it from the view state do this (C#):
if (Page.IsPostBack) {
// Read from view state
myString=(string) ViewState["MyValue"];
} else {
// Store in view state
ViewState["MyValue"] = myString;
}

Anders Norås
http://dotnetjunkies.com/weblog/anoras/
 
D

David Jessee

Or, try this....

public class CrsInstnc : System.Web.UI.Page {
private const string vs_TcoRef = "TcoRef";

private void Page_Load(object sender, System.EventArgs e) {
if(!IsPostBack){
if(Request.QueryString["ref"] != null){
this.tcoRef = Request.QueryString["ref"].ToString();
}
...
}

protected string TcoRef{
get{
return
(this.ViewState[vs_TcoRef]==null)?string.Empty:(string)this.ViewState[vs_Tco
Ref]);
}
set{
this.ViewState[vs_TcoRef]=value;
}
}
 

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,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top