0

This might be a stupid silly question, but why is this not increasing past 2?

No matter how many times I click the button the label is stuck on 2.

protected void nextBtn_Click(object sender, EventArgs e)
    {
            questions = 1;
            questions++;
            qstnLbl.Text = questions.ToString();
    }

The label is supposed to start at 1 and at button press add a number like 2-3-4 etc. Am I missing something?

3 Answers 3

1

Web is stateless. questions get initialized to 1 on each postback and hence the value is always 2;

Please change the code to as below where state is maintained using session:

protected void nextBtn_Click(object sender, EventArgs e)
{
    questions = 1;
    if (Session["questions"] != null)
       questions = (int)Session["questions"];
    questions++;
    Session["questions"] = questions;
    qstnLbl.Text = questions.ToString();
}

There are many ways to maintain state in Web. Please go through this link to get more information on that.

Sign up to request clarification or add additional context in comments.

2 Comments

Of course, session is back to haunt me, im still learning about this ASP.NET and session has been a huge pain right now. This worked perfectly, thanks a lot!
Yes, maintaining state is a challenge in ASP.NET. As i said in the answer, you can also try out other ways mentioned in the link to maintain state. Also please accept the answer so that it is clear to others.
0

Even in a console or desktop application this would not work because on every click you are re-initializing your value to 1.

Also HTTP is stateless as mentioned by other Answer.

Comments

0

Your way of incrementing value is correct but it will always be 2 because you are declaring and assigning value to question variable 1 on button click. So when you click button you get question variable holding 1 which get incremented to 2 and will be displayed in label.

So, to solve the problem you have to use something that will hold your question variable forever unless you destroy that thing. Hence for that you can use ViewState, Session or Cookie.

Using Session.

protected void nextBtn_Click(object sender, EventArgs e)
{
    int questions = Session["questions"] ==null? 1:
       Convert.ToInt32(Session["questions"]);        
    questions++;
    Session["questions"] = questions;
    qstnLbl.Text = questions.ToString();
}

Similarly you can use ViewState or Cookie instead of session.

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.