开发者

Can I assign a value to a variable which Sticks to this variable in every scope?

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

 开发者_JS百科   protected void AnotherFunction(object sender, EventArgs e)
{
    // Variable ID here is zero
}


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.


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; } }


Maybe try using readonly variables?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜