C# 每个按钮的增量数量单击C ASP.NET

C# 每个按钮的增量数量单击C ASP.NET,c#,asp.net,visual-studio,increment,C#,Asp.net,Visual Studio,Increment,可能重复: 我尝试为默认页面上的每次单击增加一个int。Int=0。它只升到1。我应该如何增加每次单击的次数 public partial class _Default : System.Web.UI.Page { private int speed = 0; public int Speed { get { return speed; } // Getter set { speed = value; } // Setter

可能重复:

我尝试为默认页面上的每次单击增加一个int。Int=0。它只升到1。我应该如何增加每次单击的次数

public partial class _Default : System.Web.UI.Page
{
    private int speed = 0;

    public int Speed
    {
        get { return speed; }  // Getter
        set { speed = value; } // Setter
    }

    public void accelerate()
    {
        //speed++;
        this.Speed = this.Speed + 1;
    }

    public void decelerate()
    {
        // speed--;
        this.Speed = this.Speed - 1;
    }

    public int showspeed()
    {
        return this.Speed;
    }

    //car bmw = new car();
    public void Page_Load(object sender, EventArgs e)
    {
        //datatype objectname = new

       dashboard.Text = Convert.ToString(this.showspeed());
    }

    public void acc_Click(object sender, EventArgs e)
    {
       this.accelerate();
       dashboard.Text = Convert.ToString(this.showspeed());
    }

    public void dec_Click(object sender, EventArgs e)
    {
        this.decelerate();
        this.showspeed();
    }
}

您需要以在回发过程中保持的方式存储结果。我建议使用ViewState,例如:

public int Speed
{
    get { 
        if(ViewState["Speed"] == null) {
             ViewState["Speed"] = 1;
        }
        return Convert.ToInt32(ViewState["Speed"]);
     }

    set { 
         ViewState["Speed"] = value;
    }
}
您可以使用来跨回发维护值:

private int Speed
{
   get
   {
       if (ViewState["Speed"] == null)
           ViewState["Speed"] = 0;
       return (int)ViewState["Speed"];
   }
   set { ViewState["Speed"] = value; }
}

因为每次单击按钮时,它都会将速度值初始化为0

HTTP是无状态的。这意味着它不会像编程中那样在回发过程中保留变量的值。因此,您需要在回发中保留该值

您可以在页面中使用隐藏元素来存储值,并在每次需要对该值执行函数时访问该值:

 <asp:HiddenField ID="hdnFileId" runat="server" Value="" />

从comment中,文本框、复选框、单选按钮控件值等控件的数据将在回发时发布到服务器,因为它们在浏览器中呈现为标准HTML表单控件。请参阅。

一个无可辩驳的证据,证明Webeems的无状态性质与此处描述的问题相同。输入值不需要通过viewstate进行维护。如果每次都是来回传递,为什么会这样?@AdrianIftode:因为hTTP是无状态的。典型输入字段中的值在回发时不可用。所有ASP.NET控件都在内部使用ViewState在回发过程中保留值。我确信此语句对输入无效,我解释道why@AdrianIftode:在此cas中,OP希望在每个按钮单击事件上获得先前更新的值,以便再次更新。对于隐藏控件,asp.net在内部使用viewstate保留该值。我相信以前保存的值应该在单击按钮时可用event@AdrianIftode当前位置我明白你的意思了。你完全正确。。我会更新我的答案。这是我今天学到的东西。非常感谢。我认为速度最好从0开始
public void Page_Load(object sender, EventArgs e)
{
    this.speed = ConvertTo.Int32(hdnFileId.Value);
}