Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change an int counter value when a button is clicked?

How can I change the counter value when Button1 is clicked and if the Button2 is clicked result.Text must have a value of 10.

public partial class Exercise2 : System.Web.UI.Page
{
      int counter = 1;
      public void Button1(object sender, EventArgs e)
      {
            counter = 10;
   
      }

      public void Button2(object sender, EventArgs e)
      {
         result.Text = The counter value is: + counter
         //Here, the counter value is always 1, I want it to be 10.
      }
}
           

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The key clue is here: System.Web.UI.Page

This is a web application, and web applications are inherently stateless. So every time a request is made to this page, an entirely new instance of this class is created. Which means counter is always 1.

You’ll need to persist the counter value somewhere. Session state, a database, a file, the client, etc. Different persistence mediums are useful for different purposes. But you’d need to use something to hold the data so it’s not being reset on every request.

For example, if you wanted to persist in session state:

public partial class Exercise2 : System.Web.UI.Page
{
    public void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            Session["counter"] = 1;
    }

    public void Button1(object sender, EventArgs e)
    {
        Session["counter"] = 10;
    }

    public void Button2(object sender, EventArgs e)
    {
         result.Text = The counter value is: + Session["counter"];
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading