How do I stop my timer when it reaches zero? I have this windows form code here:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Timers;
namespace SoftwareEngineering
{
public partial class MainGame : Form
{
int minutes = 2;
int seconds = 0;
private TimeSpan countdowntime;
public MainGame()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
}
private void NewGame_Click(object sender, EventArgs e)
{
setcountdown(minutes, seconds);
timer1.Enabled = true;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan tSecond = new TimeSpan(0, 0, 1);
countdowntime = countdowntime.Subtract(tSecond);
if(seconds > 0)
{
timeremaining.Text = countdowntime.Minutes.ToString() + ":" + countdowntime.Seconds.ToString();
}
else
{
timeremaining.Text = "Times Up!";
timer1.Stop();
}
}
private void setcountdown(int min,int sec)
{
TimeSpan temp = new TimeSpan(0 , min , sec);
countdowntime = temp;
}
The code works but once it reaches "0:0" , it will continue to decrement to "0:-1" and so on, my condition doesn't seem to work when stopping the timer.
This is my condition from the above:
if(seconds > 0)
{
timeremaining.Text = countdowntime.Minutes.ToString() + ":" + countdowntime.Seconds.ToString();
}
else
{
timeremaining.Text = "Times Up!";
timer1.Stop();
}