Timer Tick not increasing values on time interval

后端 未结 3 481
野的像风
野的像风 2020-12-10 16:52

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.



        
相关标签:
3条回答
  • 2020-12-10 17:18

    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();
    }
    
    0 讨论(0)
  • 2020-12-10 17:28

    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();
    }
    
    0 讨论(0)
  • 2020-12-10 17:34

    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;
    }
    
    0 讨论(0)
提交回复
热议问题