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