Reputation: 339
Take a look at this code.
Label lb=new Label();
string prev="val";
protected void Button3_Click(object sender, EventArgs e)
{
prev = "temp";
lbl.ID =prev;
lbl.Text =prev;
Panel1.Controls.Add(lbl);
}
I had break point at start of button3 event. I see that the value in prev again changed to 'val' everytime the button event is fired. Isn't it has to be 'temp'?
Upvotes: 0
Views: 115
Reputation: 732
Upvotes: 1
Reputation: 6696
Because in ASP.NET
server side, on every call a new object of the page's class will be created. If you want to keep the value between calls, you can do one of this, based on your needs
static
: I do not recommend this approach, because when the application restarts, the last value will be lost, but in other 2 options there is solutions to keep the values over application restarts.Session
to store it : Use this if you need different values per user Application
to store it : Use this if you need one value for all usersNote: Don't forget to lock your variable on change, because of concurrency issues.
Upvotes: 3
Reputation: 186
Every time the page Post backs on Button Click event, your variable gets initialized again in asp.net. To avoid this you can save the values of variable in one of the state management techniques. example: Session
Session["prev"]="val";
In button click you can set this value by using
Session["prev"]="temp";
to recall this value you can use
string variable=Convert.ToString(Session["prev"]);
Hope this will help.
Upvotes: 2