question

Nedudale-0390 avatar image
0 Votes"
Nedudale-0390 asked karenpayneoregon answered

How can I change the time counter direction if to count up or down ?

 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;
    
 namespace Extract
 {
     public partial class TimeCounter : Label
     {
         private Timer _timer;
         private int _elapsedSeconds;
    
         public TimeCounter()
         {
             InitializeComponent();
    
             _timer = new Timer
             {
                 Interval = 1000,
                 Enabled = true
             };
             _timer.Tick += (sender, args) =>
             {
                 _elapsedSeconds++;
                 TimeSpan time = TimeSpan.FromSeconds(_elapsedSeconds);
                 this.Text = time.ToString(@"hh\:mm\:ss");
             };
         }
    
         private void TimeCounter_Load(object sender, EventArgs e)
         {
    
         }
     }
 }

I tried to change the line _elapsedSeconds++; to _elapsedSeconds--; but it's keep counting up. I want to be able to change the counter either to count down or up.

dotnet-csharpwindows-forms
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered

In the following example, the Timer was dropped from the ToolBox.

 using System;
 using System.Windows.Forms;
    
 namespace TimerUpDown
 {
     public partial class Form1 : Form
     {
         public Form1()
         {
             InitializeComponent();
         }
    
         private bool _direction;
         private int _seconds;
         private int _highValue = 10;
         private int _lowValue = 0;
    
         private void button1_Click(object sender, EventArgs e)
         {
             timer1.Enabled = false;
             _direction = checkBox1.Checked;
             _seconds = _direction ? _lowValue : _highValue;
             timer1.Enabled = true;
         }
         private void timer1_Tick(object sender, EventArgs e)
         {
             if (_direction)
             {
                 _seconds++;
             }
             else
             {
                 _seconds--;
             }
               
             label1.Text = TimeSpan.FromSeconds(_seconds).ToString("mm\\:ss");
    
             if (_seconds == _lowValue || _seconds >= _highValue)
             {
                 timer1.Enabled = false;
             }
    
         }
     }
 }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.