Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer Tick not increasing values on time interval

Tags:

c#

asp.net

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();
}
like image 383
Jitender Avatar asked Nov 05 '18 09:11

Jitender


People also ask

What is tick in timer?

When the timer is started, the timer register increments to 1, then 2, then 3, and so on. The timer increments, or ticks, at a precise rate, which you configure. The timer keeps ticking (incrementing) all the way up to the maximum value that can be stored in a 16-bit register, which is 0xFFFF (== 65535 decimal).

Is a timer based change of value?

A timer's current value can be changed at any time, including when the timer is active. The new value can be either greater or smaller than the previous value; storing 0 into a timer's current value stops it immediately.


2 Answers

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;
}
like image 89
VDWWD Avatar answered Oct 22 '22 18:10

VDWWD


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();
}
like image 35
Hary Avatar answered Oct 22 '22 18:10

Hary