计数器won't递增多于一次onclick

本文关键字:于一次 onclick won 计数器 | 更新日期: 2023-09-27 18:15:05

我有一个计数器,onclick应该增加1,它在点击时这样做,但如果我再次点击按钮,它不会再增加。相反,它将停留在1。如果按钮被点击多次,我如何让它向上?

 protected void submitAnswerButton_Click(object sender, EventArgs e)
    {
  int counter = 0;
  if (mathAnswerTextBox.Text == answer.ToString())
        {
            answerStatus.Text = "Correct!";

        }
        else if (mathAnswerTextBox.Text != answer.ToString())
        {
            answerStatus.Text = "Incorrect";
            counter++;

            if (counter == 1)
            {
                incorrectStrikes.Text = counter.ToString();
            }
            else if (counter == 2)
            {
                incorrectStrikes.Text = counter.ToString();
            }
            else if (counter == 3)
            {
                incorrectStrikes.Text = counter.ToString();
            }
        }

计数器won't递增多于一次onclick

您需要使counter在方法之外,如类中的字段,而不是局部变量:

private int counter = 0;
protected void submitAnswerButton_Click(object sender, EventArgs e)
{
  if (mathAnswerTextBox.Text == answer.ToString())
    {
        answerStatus.Text = "Correct!";
  ...
罢工

由于这是一个web应用程序,您可能希望将计数器存储在会话中,例如:

Inside Page_Load:

if(!IsPostback)
{
   Session["AttemptCount"] = 0
}

然后在

里面
protected void submitAnswerButton_Click(object sender, EventArgs e)
{
  int counter = (int)Session["AttemptCount"];
  if (mathAnswerTextBox.Text == answer.ToString())
    {
        answerStatus.Text = "Correct!";
  ...
  //Make sure you include this on all paths through this method that
  //affect counter
  Session["AttemptCount"] = counter; 

因为你的counter是一个局部变量(如下面的代码所示),所以每次你点击按钮,它将被初始化为0,因此你每次都会得到1,因为它会增加一次。

 protected void submitAnswerButton_Click(object sender, EventArgs e)
    {
  int counter = 0;

您需要将值存储在一个更全局的上下文中,例如ViewState或Session,甚至可能是一个HiddenField来存储值。

结论:Web是无状态的,所以你需要一个状态管理器。

protected void submitAnswerButton_Click(object sender, EventArgs e)
{
    var counter = this.ViewState["foo"] as int; // read it from the ViewState from the previous request, or set it to default(int) = 0 with as
    // ... do your routine
    this.ViewState["foo] = counter; // write it back to store it for the next request
}

无论如何-这只是有效的在一个网络上下文中,你是无状态的。

如果你是在webform/wpf-context中,你宁愿选择一个简单的static,或者实例变量,或者…