Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment number every time button is click

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();
}
like image 564
rai nalasa Avatar asked Mar 12 '23 03:03

rai nalasa


2 Answers

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();
}
like image 84
Siyavash Hamdi Avatar answered Mar 24 '23 14:03

Siyavash Hamdi


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 ; }
}
like image 42
mohsen Avatar answered Mar 24 '23 12:03

mohsen