yukiko
yukiko

Reputation: 53

Timer and Buttons Issues

I'm doing a project using Visual Studio 2013 using C#. I want the timer to countdown from 120 minutes to 0 minutes and when it reaches 0, a message box will show that the time is up. I also want the timer to reset when the reset button is pressed. However, when I pressed the reset button, even though the timer is reset, I pressed the start button and the message box "Time's up" would appear and the timer would not start. Please help me. I'm a total newbie to C# so please try not to give me complicated answers that is hard to understand. Also, you will see me around a lot more because I'll have more questions to ask. Thanks!! (This are my codes.)

    private void startbutton_Click(object sender, EventArgs e)
    {
        timer.Enabled = true;
        foreach (var button in Controls.OfType<Button>())
        {
            button.Click += button_Click;
            timer.Start();
            button.BackColor = Color.DeepSkyBlue;
        }
    }

    private void stopandresetbutton_Click(object sender, EventArgs e)
    {
        button.BackColor = default(Color);
        timer.Stop();
        timeleft = 0;
        timerlabel.Hide();
    }

    int timeleft = 120;
    private void timer_Tick(object sender, EventArgs e)
    {
        if (timeleft > -1)
        {
            timerlabel.Text = timeleft + " minutes";
            timeleft = timeleft - 1;
        }
        else
        {
            timer.Stop();
            MessageBox.Show("Time's up!");
        }
    }

Upvotes: 5

Views: 141

Answers (1)

Sweeper
Sweeper

Reputation: 274443

Your error is at the stopandresetbutton_Click method. You should not set the timeLeft variable to 0. Because you want to reset the timer, you should set it to 120 (If your unit is mins).

OR

You set the timeLeft variable to 120 in the startbutton_Click method. That way it works as well

For a better approach

You can write a property like this

private int TimeLeft {
    get {return timeLeft; }
    set {
        timeLeft = value;
        timerlabel.Text = timeleft + " minutes";
    }
}

That way you can set TimeLeft to some value and the label's text will change as well. This is because you might not remember to change the label's text after you set the value of timeLeft.

Upvotes: 3

Related Questions