用户单击asp.net Web应用程序图像按钮时更新计数器

时间:2018-09-28 18:36:15

标签: c# asp.net imagebutton

我有一个ASP.NET Web窗体应用程序,用户可以在其中打开ImageButton控件上的图像。在定义方法之前,我将全局int变量“ counter”设置为零。每次用户单击ImageButton控件时,“计数器”应该增加一。与ImageButton关联的OnClick方法正在触发,但是我认为每次单击后都会重置“计数器”。我知道这是因为只有Image_Click中的if分支正在执行。如何确保每次点击都记住更新的“计数器”值?

这是ImageButton的.aspx代码:

<asp:ImageButton ID="pic" runat="server" OnClick="Image_Click" />

这是Image_Click的C#代码:

public int numClick++;

protected void Image_Click(object sender, ImageClickEventArgs e)
{
    numClick++;

    if (numClick % 2 == 1)
    {
        pos1x = e.X;
        pos1y = e.Y;
        labelarea.Text = " " + pos1x;

    }
    else if (numClick % 2 == 0)
    {
        pos2x = e.X;
        pos2y = e.Y;
        distx = Math.Abs(pos2x - pos1x);
        disty = Math.Abs(pos2y - pos1y);
        redistx = (int)(Math.Ceiling((float)(distx / (zoom * Math.Floor(dpiX / 4.0)))));
        redisty = (int)(Math.Ceiling((float)(disty / (zoom * Math.Floor(dpiY / 4.0)))));
        if (mode == 1)
        {
            if (distx >= disty)
            {
                lengthlabel.Text = "Length: " + redistx;
                total += redistx;
            }
            else
            {
                lengthlabel.Text = "Length: " + redisty;
                total += redisty;
            }
            labeltotal.Text = "Total: " + total;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您必须将点击计数存储在Sesson或Viewstate中,因为确实在每次加载页面后都会将其重置。与应用程序不同,网站变量仅在页面执行期间存在。 下面是一个简单的示例,说明如何在PostBack上持久保存变量。

protected void Image_Click(object sender, EventArgs e)
{
    //create a variable for the clicks
    int ButtonClicks = 0;

    //check if the viewstate exists
    if (ViewState["ButtonClicks"] != null)
    {
        //cast the viewstate back to an int
        ButtonClicks = (int)ViewState["ButtonClicks"];
    }

    //increment the clicks
    ButtonClicks++;

    //update the viewstate
    ViewState["ButtonClicks"] = ButtonClicks;

    //show results
    Label1.Text = "Button is clicked " + ButtonClicks + " times.";
}