Search code examples
c#winformstimerclick

Timer component not stopping


I'm working with a Winforms app and I'm tyring to make a label "glide" up when a user clicks on it. To do this, I've created a click event that starts a timer, which then gradually moves the label up the form. I then have a counter that I increment, and when the counter reaches a certain position, the timer should stop. The timer is not stopping, however. I've deliberately set the counter limit to 2 for testing purposes, but the label continues to fly off the form. Here is the code:

private void DrawerTimer_Tick(object sender, EventArgs e)
    {
        int counter = 0;
        newsLabel.Top -= 10;
        counter++;
        if (counter == 2)
            drawerTimer.Stop();
    }

    private void News_Click(object sender, EventArgs e)
    {
        drawerTimer.Start();
    }

Solution

  • int counter = 0; // here you are setting it 0
    newsLabel.Top -= 10;
    counter++; // here you are incrementing it by 1
    if (counter == 2) // here you are checking for 2, its never going to get there
       drawerTimer.Stop();
    

    More than likely you will want to do something like this

    private int _counter; // instance field, field to remember your count
    
    private void DrawerTimer_Tick(object sender, EventArgs e)
    {
        newsLabel.Top -= 10;
        counter++; // increment it every tick
        if (counter == 2)
            drawerTimer.Stop();
    }
    
    private void News_Click(object sender, EventArgs e)
    {
        _counter = 0; // set to zero when start
        drawerTimer.Start();
    }