So I am trying to set my countdown timer intervals, so that 1hr = 10minutes (in real time), 1min = 10secs (In real time) and 1s = 0.17s (In realtime) to help when testing my code. I can't seem to find what part of my code to change without causing an error. so I tried defining the interval in the initialise components section and received this:
System.NullReferenceException: 'Object reference not set to an instance of an object.' timer was null.
private void button1_Click(object sender, EventArgs e)
{
AddTimeToClock(TimeSpan.FromSeconds(10));
}
private void Form1_Load(object sender, EventArgs e)
{
timer = new System.Windows.Forms.Timer();
timer.Interval = (int)TimeSpan.FromSeconds(1).TotalMilliseconds;
timer.Tick += OnTimeEvent;
DisplayTime();
}
private void DisplayTime()
{
lblTime.Text = countdownClock.ToString(@"hh\:mm\:ss");
}
private void OnTimeEvent(object sender, EventArgs e)
{
// Subtract whatever our interval is from the countdownClock
countdownClock = countdownClock.Subtract(TimeSpan.FromMilliseconds(timer.Interval));
if (countdownClock.TotalMilliseconds <= 0)
{
// Countdown clock has run out, so set it to zero
// (in case it's negative), and stop our timer
countdownClock = TimeSpan.Zero;
timer.Stop();
}
// Display the current time
DisplayTime();
}
private void AddTimeToClock(TimeSpan timeToAdd)
{
// Add time to our clock
countdownClock += timeToAdd;
// Display the new time
DisplayTime();
// Start the timer if it's stopped
//if (!timer.Enabled) timer.Start();
}
private void button2_Click(object sender, EventArgs e)
{
AddTimeToClock(TimeSpan.FromMinutes(1));
}
private void button3_Click(object sender, EventArgs e)
{
AddTimeToClock(TimeSpan.FromMinutes(10));
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked) timer.Start();
else
{
timer.Stop();
}
}