variable initialized in class loses its previous value with the page loading

I’ve declared a String variable test with “hi”. every time I click on Button1, I expect that test will be appended with its previous value. But I have noticed that it loses its previous value when the button is clicked and the page is reloaded. That is every time I click it, it has its text as “hihi”. I expect “hihihihi” on the next click and so on. What’s the problem here with the code below?

public partial class _Default : System.Web.UI.Page
{

    String test = "hi";

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        test += test;
        Button1.Text = test;
    }
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

No, that’s not the way asp.net works. If you need that behavior you should do this:

public string test {
  get {
    return (string) ViewState["test"] ?? "hi";
  }
  set {
    ViewState["test"] = value;
  }
}

When ASP.NET sends a request to the server, a new version of your class is instantiated. If you need to get the state, you need to use ViewState (which is saved in a hidden field in the browser and sent with every request, and therefore state saved per page), or you can use SessionState which is a state saved per user. SessionState by default is saved in memory. So, if you restart IIS, this state will go away. Note that viewstate’s state will NOT go away if you reset IIS (since it’s being sent by the browser). You can also use the Cache which again, is saved in memory. This state is for all users of your application. The same rules about resetting IIS apply. Finally, you could make your variable static. As I said, every time a request is made a new version of your class is instantiated. Of course, static variables are not instance variables, so the state of a static variable is saved across postbacks as well. The same rules about IIS reset apply to static variables as Cache and Session.

Method 2

A field only exists for the duration of a single request. If you want it to live between requests you’ll have to use something like session-state, view-state, a cookie, or a HTML form / request value.

In most “real” applications, you can’t even guarantee that subsequent requests are being handled by the same physical machine.

Method 3

Every time you visit a page, a new instance of the page is created with its own copy of your local variable. There are several ways you can persist values from one page view to the next, and they are all described here: ASP.NET State Management Overview

Method 4

String test = "hi";

This is a private, instance class field.

You need a static one if you want to achieve your goal.

BTW, honestly, maybe you’re looking to use a session item:

HttpContext.Current.Session["test"] = "hi";

Doing this way you’ll have a code like this in your event handler:

string currentTestText = (string)HttpContext.Current.Session["test"];

currentTestText += currentTestText;
Button1.Text = currentTestText;

HttpContext.Current.Session["test"] = currentTestText;

Method 5

Thats because a button generates a POST BACK you could declare the variable as a Static Property or Create a Session[“Test”] or add some code on the button click if IsPostback {}

Method 6

The problem with your code is that on every request your Page instance is recreated so test won’t keep the previous value since it belongs a new Page instance.

This is the flow:

Request 1 Start

Page is created -> test = "hi"

Request 1 Ends

Page is detroyed

Request 2 Start

Page is created -> test = "hi"

Request 2 Ends

Page is detroyed

Method 7

Remember that on a postback the asp.net recreates the objects and reassigns the values. In your case the test variable gets recreated and gets assigned the value of ‘hi’. You might want to store the variable in session and then append the value.

Method 8

This works, just try it

// in the page load event
if(!this.IsPostBack)
   Button1.Text = test;

// in the Click event
this.Button1.Text += test;

The problem with your current code is that you are assigning an instance variable to the button text, since it is an instance variable it is being initialized every time you request the page with the same value that’s why you always get hihi only and not hihihihihihihi

Every time you click the button, ASP.Net creates a new Page(), therefore the test member will always be initialized like: test = "hi";.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x