setting a global variable once and for all

F

Fred Exley

The first time I enter a page, I want to set a variable once, and have that
variable retain its value from that point on. So on the first time in the
program, I set runLoc = "yes". When I then call routine validatex, the
variable retains it's value. But when I call routine validatex from the
button click event, variable runLoc is null. How can I retain the value of
runLoc permanently? thanks


Here's the complete program:

using System;

public partial class scopeTest : System.Web.UI.Page
{
public string runLoc;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // first pass:
{
runLoc = "yes";
}
validatex();
}

protected void Button1_Click(object sender, EventArgs e)
{
validatex();
}

protected void validatex()
{
string b = runLoc;
}

}
 
M

Mark Fitzpatrick

Try this:

public string runLoc
{
get{
if(ViewState["runLoc"] != null)
return ViewState["runLoc"].ToString();
else
return string.empty;
}
set
{ ViewState["runLoc"] = value; }
}

That will essentially create a property that save/stores the value in the
viewstate. The only way you can maintain a variable is to use the viewstate.
Of course, any viewstate changes will only occur on postback, but this is
good to get things initially set. You may have to toy with setting the
variable at the right point, in other words before the page saves the
viewstate so you may have to play with the correct event to set it within.
 
F

Fred Exley

Hey, it worked! thanks much. I was also wondering if setting a session
variable would be appropriate to use, or making a public dataset, but hadn't
yet heard of using a ViewState. In my limited exposure to the .Net
Framework, it seems I can always get whatever I'm trying to do to work, one
way or another, but I'm never sure whether I'm implementing an elegant
solution or an idiotic one. thanks again
 

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

Top