每次单击按钮时增加数字

rai*_*asa 4 c# asp.net increment

每当我单击按钮时,我想增加一个int变量。i但我得到的只是int的值1,并且不再增加。

这是我的代码:

private int i;

protected void btnStart_Click(object sender, EventArgs e)
{
    i++;

    lblStart.Text = i.ToString();
}
Run Code Online (Sandbox Code Playgroud)

Siy*_*mdi 5

通过每个请求(单击按钮),将创建一个新实例。所以你的非静态变量将被重置为0.

您可以定义i为静态:

private static int i;
protected void btnStart_Click(object sender, EventArgs e)
{
    i++;

    lblStart.Text = i.ToString();
}
Run Code Online (Sandbox Code Playgroud)

但请注意,该i变量在所有用户之间共享。为了改善这个问题,你可以使用Session.

Session是一种在会话中存储每个用户的数据的能力。

因此,您可以使用以下属性来更改i每个会话中的变量:

private int i
{
    get
    {
        if (Session["i"] == null)
            return 0;

        return (int)Session["i"];

        // Instead of 3 lines in the above, you can use this one too as a short form.
        // return (int?) Session["i"] ?? 0;
    }
    set
    {
        Session["i"] = value;
    }
}

protected void btnStart_Click(object sender, EventArgs e)
{
    i++;

    lblStart.Text = i.ToString();
}
Run Code Online (Sandbox Code Playgroud)