taji01 taji01 - 26 days ago 15
C# Question

Time span subtract stopwatch countdown

I'm using WinForm's. I have a label in my form that should count down from 0:20 seconds. to 0:00 seconds. I'm trying to do this here, but the compiler gives me an error.


Error: Cannot convert from 'int' to 'System.TimeSpan'


Why cant I use timespan.Subtract()? and how could I count down from 0:20 to 0:00 seconds?

private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan timespan = TimeSpan.FromSeconds(20);

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Time_label.Text = timespan.Subtract(stopwatch.Elapsed.Seconds);
}

Jim Jim
Answer

A better approach for a simple second counter would be to make use of the Timer itself.

private readonly Timer _timer;    
private TimeSpan _timespan;
private readonly TimeSpan _oneSecond;

public Form1()
{
    InitializeComponent();

    _timer = new Timer();
    _timer.Tick += timer1_Tick;
    _timer.Interval = 1000;       

    _timespan = TimeSpan.FromSeconds(20);
    _oneSecond = new TimeSpan(0, 0, 0, 1);

    _timer.Start();
}

private void timer1_Tick(object sender, EventArgs eventArgs)
{
    if (_timespan >= TimeSpan.Zero)
    {
        Time_label.Text = _timespan.ToString(@"m\:ss");
        _timespan = _timespan.Subtract(_oneSecond);
    }
    else
    {
        _timer.Stop();
    }
}
Comments