I am currently trying to learn how to use session state but I have run into a problem that I can't figure out. What I am trying to do is have a button that when I click it, it will increase the value of my variable by 1, but my problem is that the first three times I click it my int does not increase but on the fourth click it works as intended and increases.
This is my code.
private static int Clicks = 1;
protected void Page_Load(object sender, EventArgs e)
{
// First page load?
if (!IsPostBack)
{
Session["Clicks"] = Clicks; //Clicks
}
Label1.Text = Convert.ToString(Session["Clicks"]);
}
protected void btnCounter_Click(object sender, EventArgs e)
{
//UserClick.BtnClicks++;
Session["Clicks"] = Clicks++;
}
You should look at the ASP.NET Page Lifecycle (see Postback Event Handling).
That btnCounter
click event won't get fired until after the Page_Load
event. You will probably have better results if you update the Label
within your Click
event.
protected void btnCounter_Click(object sender, EventArgs e)
{
Session["Clicks"] = Clicks++;
Label1.Text = Session["Clicks"].ToString();
}