I want to increase an int
variable i
whenever I click on a button. But what I get is only int
value of 1
and it doesn't increase anymore.
Here is my code:
private int i;
protected void btnStart_Click(object sender, EventArgs e)
{
i++;
lblStart.Text = i.ToString();
}
By each request (Clicking on the button), a new instance will be created.
So your non-static variable will be reset to 0
.
You can define i
as static:
private static int i;
protected void btnStart_Click(object sender, EventArgs e)
{
i++;
lblStart.Text = i.ToString();
}
But please note that the i
variable is shared between all the users.
To improve this issue, you can use Session
.
Session
is an ability to store data of each user in a session.
So you can use following property to change the i
variable in each session:
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();
}
As you know other answer is correct i want add another answer
You must in webform save your variables in ViewState
Just define your variables like this
public int i
{
get { Convert.ToInt32( ViewState["i"] ); }
set { ViewState["i"] = value ; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With