1

I am not a good programmer, it's rather my hobby. So please don't judge me for being bad at programming. This is my current code ive made for the countdown timer.

int i = 000000;
private void timer1_Tick(object sender, EventArgs e)
{
   {
            i++;
            textBox1.Text = i.ToString() + "00:00:00";
   }
}

When I run the timer. then the TextBox1 isn't showing 00:00:01, but it's showing 100;00;00. Thank you for reading my post and again, sorry for having soo bad programming knowledge.

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Jaan Suur
  • 41
  • 1
  • 6

3 Answers3

8

You can use this:

TimeSpan time = TimeSpan.FromSeconds(i);
textBox1.Text = time.ToString(@"hh\:mm\:ss");
1

Ok, so you know how to use Timer but your problem is with string, when you use + on string you are concatenating them, so say "hello" + " world" is equal to "hello world", so when you concat i with 00:00:00 the output you see is very logical.
you can use snippet below to achieve your goal(just replace your form class content with this)

private Timer _timer;
private Label _label;
private int _elapsedSeconds;
public Form1()
{
    _timer = new Timer
    {
        Interval = 1000,
        Enabled = true
    };
    _timer.Tick += (sender, args) =>
    {
        _elapsedSeconds++;
        TimeSpan time = TimeSpan.FromSeconds(_elapsedSeconds);
        _label.Text = time.ToString(@"hh\:mm\:ss");
    };

    _label = new Label();

    Controls.Add(_label);
}

Edit

Tnx to @Juliet Wilson I edited how time is converted to string

hessam hedieh
  • 780
  • 5
  • 18
  • Though you start off with a nice description of the immediate problem, your code solution is kinda convuluted. Why not use `ToString()` as per **Juliet's** answer instead of the fidly hour/min/sec calculation? –  Jan 19 '19 at 10:00
  • @shash678, tnx for the link, but my naming convention is taken from Jetbrain reharper – hessam hedieh Jan 19 '19 at 10:05
  • downvote removed. thanks for improving your answer :) –  Jan 19 '19 at 10:06
0

I would suggest to use Stopwatch for that. It will do the magic you need. Here you can find good example of using Stopwatch class in C# https://www.dotnetperls.com/stopwatch.

Gaurav
  • 782
  • 5
  • 12
  • Please mark it as answer as it resolved your problem. – Gaurav Jan 19 '19 at 09:54
  • Well no, not only wouldn't address the immediate problem (formatting), `StopWatch` doesn't have any _count-down_ ability at all. –  Jan 19 '19 at 09:58
  • @MickyD, although user has stated countdown in question, but looking at code he implied something else – hessam hedieh Jan 19 '19 at 10:00
  • @hessamhedieh That's true. The answer is borderline comment with a link to a foreign site. Perhaps if author improves answer I'll upvote :) –  Jan 19 '19 at 10:05