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

Time:09-01

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

CodePudding user response:

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

CodePudding user response:

Use ViewState instead of using int count, because ViewState preserve the value and controls.

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

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

}

  • Related