【发布时间】:2014-07-28 06:45: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();
}
}
【问题讨论】:
-
将
int counter移到方法外。 -
@Sayse 我怀疑这将是 the 解决方案。实例成员和静态成员之间仍然存在差异......
-
@AndreasNiedermair - 这与它有什么关系? - 另外,您可能希望阅读此内容 - Variable and Method Scope in Microsoft .NET
-
@Sayse 再次阅读了这个问题:“但如果我再次单击该按钮,它就不会再次增加。” ...所以你需要一个线程独立值并以某种方式将后续点击附加到正确的 instance(例如 ThreadStatic,它在 web 上下文中不起作用)
-
@AndreasNiedermair - 我们不知道 OP 正在构建什么样的应用程序。他们的术语可能被解释为表明它是一个网络应用程序,但这绝不是肯定的(如果是,那么
Session是解决问题的明显位置)