Jam
Jam

Reputation: 339

Why is the global string getting empty at every call?

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

Answers (3)

Mohsin
Mohsin

Reputation: 732

  1. Declare 'prev' variable in some global class.
  2. Declare it static
  3. Use one instance of class for whole application
  4. Store in Session
  5. Store in Application

Upvotes: 1

Taher  Rahgooy
Taher Rahgooy

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

  1. Make the variable 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.
  2. Use Session to store it : Use this if you need different values per user
  3. Use Application to store it : Use this if you need one value for all users

Note: Don't forget to lock your variable on change, because of concurrency issues.

Upvotes: 3

Vijay
Vijay

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

Related Questions