Timer Tick not increasing values on time interval

I want to increase values on timer tick event but it is not increasing don’t know what I am forgetting it is showing only 1.

<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick" Interval="1000"></asp:Timer>

private int i = 0;

protected void Timer1_Tick(object sender, EventArgs e)
{
    i++;

    Label3.Text = i.ToString();
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use ViewState to store and then read the value of i again.

int i = 0;

protected void Timer1_Tick(object sender, EventArgs e)
{
    //check if the viewstate with the value exists
    if (ViewState["timerValue"] != null)
    {
        //cast the viewstate back to an int
        i = (int)ViewState["timerValue"];
    }

    i++;

    Label3.Text = i.ToString();

    //store the value in the viewstate
    ViewState["timerValue"] = i;
}

Method 2

Check whether the form is posted back and then assign values. Check IsPostBack

private int i;

protected void Timer1_Tick(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        i = 0;
    }
    else
    {
        i = Int32.Parse(Label3.Text);
        i++;           
    }

    Label3.Text = i.ToString();
}

Method 3

Generally speaking it is not a good practice to store values inside of views (such as asp.net page). It could be overwritten each time the request is sent.

You could store your data elsewhere:

public static class StaticDataStorage
{
    public static int Counter = 0;
}

And use it:

protected void Timer1_Tick(object sender, EventArgs e)
{
    StaticDataStorage.Counter++;
    Label3.Text = StaticDataStorage.Counter.ToString();
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x