1

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

2 Answers 2

2

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"];
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, for the detailed explanation @David. It finally worked :)
0

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.