tags:

views:

71

answers:

3

Can I assign a value to a variable (int) and never lose this value inside any scope ?
the problem is I am assigning the value to the variable in some scopes but the variable returns to its default value (zero) in other scopes.. Example :

    protected void Button_AddNewCourse_Click(object sender, EventArgs e)
{
    ID = 10;
}

so when I am trying to use ID in other functions it falls back to zero

    protected void AnotherFunction(object sender, EventArgs e)
{
    // Variable ID here is zero
}
A: 

Maybe try using readonly variables?

CyberDude
+4  A: 

At a guess, perhaps you're a newcomer to ASP.NET and haven't figured out why page-level variables don't keep their state between postbacks. Try reading up on Session state and Viewstate

Or for a general overview: ASP.NET State Management Overview

e.g. based on your code example, you could use a Session entry to store the value:

protected void Button_AddNewCourse_Click(object sender, EventArgs e)
{
    Session["ID"] = 10;
}

protected void AnotherFunction(object sender, EventArgs e)
{
    int tempID = (int)Session["ID"];
}

There's lots of other things you could also do - use Viewstate, for example.

codeulike
+3  A: 

Change the line that looks similar to this (which is probably somewhere):

 public int ID { get; set;}

to something like

// keep the value of ID in this page only
public int ID { get { return (int)ViewState["ID"]; } set { ViewState["ID"] = value; } }

or

// keep the value of ID in every page
public int ID { get { return (int)Session["ID"]; } set { Session["ID"] = value; } }
Jan Jongboom
that's exactly what I am looking for ,thanks!...BUT how can I do that with a desktop application in c# (no asp.net) ?
fadi
With `public static int ID { get; set; }` and then call the variable like `SomeForm.ID`.
Jan Jongboom