Problems with the timer and buttons

I am doing a project using Visual Studio 2013 using C #. I want the timer to count from 120 minutes to 0 minutes, and when it reaches 0, a message box will show that the time is increasing. I also want the timer to reset when the reset button is pressed. However, when I pressed the reset button, even if the timer was reset, I pressed the start button, and the β€œTime up” message box will appear, and the timer will not start. Please help me. I am a complete newbie in C #, so please try not to give me complex answers that are hard to understand. In addition, you will see me much more, because I will have additional questions. Thank you !! (These 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 up!"); } } 
+5
source share
1 answer

Your error is indicated in the stopandresetbutton_Click method. You should not set the timeLeft variable to 0. Since you want to reset the timer, you must set it to 120 (if your device is minimal).

OR

You set the timeLeft variable to 120 in the startbutton_Click method. So it works also

For a better approach

You can write a property like this

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

This way you can set TimeLeft to some value, and the label text will also change. This is because after setting the timeLeft value, you cannot change the label text.

+3
source

All Articles