按钮点击事件不能正常工作

问题描述:

这下面code手柄按钮单击事件。当用户点击它第一次设置拉布勒作为第一时间,当用户点击第二次它设置为拉布勒第二时间。但它不能正常工作。当我第一次点击它,它设置为拉布勒第一时间,这是正确的,但是当我点击第二次,没有什么happend。

This following code handle button click event. When the user click first time it sets the lable as "First Time", and when the user click second time it sets the lable as "Second Time". But it doesn't work properly. When I first click it, it sets the lable as "First time", which is correct, but when I click second time, nothing happend.

我的code:

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

    if (counter == 0)
    {
        lable1.Text="First Time";
        counter++;
    }
    else if (counter == 1)
    {
        lable1.Text="Second Time";
        counter--;
    }

    }

我怎样才能解决这个问题?

How can I fix it?

计数器实例字段的值不会被保存在回传。你需要存储计数的ViewState 会话或一些其他的持久化存储,两者是比较合适的。例如:

The values of instance fields like counter are not saved across postbacks. You need to store counter in ViewState, Session, or some other persistent store, whichever is more appropriate. For example:

private int Counter
{
    get { return ((int?)this.ViewState["Counter"]).GetValueOrDefault(); }
    set { this.ViewState["Counter"] = value; }
}

然后引用 this.Counter 而不是 btnCompTagUpdate_Click $ C $计数器 C>。