计数器不会在onclick上多次增加

时间:2014-07-28 06:45:06

标签: c# asp.net

我有一个计数器,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();

            }
        }

3 个答案:

答案 0 :(得分:4)

您需要在方法之外设置counter,例如类中的field,而不是局部变量:

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

<击>

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

内部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; 

答案 1 :(得分:3)

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

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

答案 2 :(得分:0)

您需要将值存储在更全局的上下文中,例如ViewStateSession或甚至HiddenField来存储值。

Conclusio: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或实例变量,或......(无论你当前需要什么,架构......)