Increment number per button click C# ASP.NET [duplicate]

你说的曾经没有我的故事 提交于 2020-01-26 04:38:05

问题


Possible Duplicate: Button click event doesn't work properly

I try to increment an int for each click on a default page. Int=0. It only goes up to 1. What should I do to increment the number for each click?

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();
    }
}

回答1:


You could use the ViewState to maintain the value across postbacks:

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



回答2:


You need to store the result in a way that will persist over postback. I suggest using ViewState, for example:

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

    set { 
         ViewState["Speed"] = value;
    }
}



回答3:


Because everytime when you click on the button, it is initializing the value of speed to 0.

HTTP is stateless. That means it wil not retain the values of variable across your postback like you do in Windows Forms programming. So you need to keep the value across your postbacks.

You can use a hidden element in your page to store the value and access the value every time you want to do a function on that:

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

and in your page load, you can read the value and load it to your variable.

public void Page_Load(object sender, EventArgs e)
{
    this.speed = ConvertTo.Int32(hdnFileId.Value);
}

From Adrianftode's comment, the data for the controls like TextBox, Checkbox, Radio button controls values will be posted to the server on the postback because they are rendered as standard HTML form controls in the browser. See Chapter 4. Working with ASP.NET Server Controls.



来源:https://stackoverflow.com/questions/9968488/increment-number-per-button-click-c-sharp-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!