taji01 taji01 - 1 year ago 101
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();
Time_label.Text = timespan.Subtract(stopwatch.Elapsed.Seconds);

Jim Jim
Answer Source

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()

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

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


private void timer1_Tick(object sender, EventArgs eventArgs)
    if (_timespan >= TimeSpan.Zero)
        Time_label.Text = _timespan.ToString(@"m\:ss");
        _timespan = _timespan.Subtract(_oneSecond);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download