Search code examples
c#winformsvariablestimercountdown

How to create an advanced countdown timer


Well, this question is related to this one, so you guys can understand it better

My Answer to it:

txtAtiv.Text = dataGridView1.Rows[0].Cells[1].Value + "";

string value = dataGridView1.Rows[0].Cells[2].Value + "";
lblLeft.Text = value.Split(' ')[1];
textStatus.Text = "";

DateTime timeConvert;
DateTime.TryParse(value, out timeConvert);

double time;
time = timeConvert.TimeOfDay.TotalMilliseconds;

var timeSpan = TimeSpan.FromMilliseconds(time);

lblSoma.Text = timeSpan.ToString();
timer2.Start();

According to the answer I wrote right there, I want to know if there's a way I can apply it to a timer and do the DataGrid values (converted) turn into a timer value. So if I press a button they start the countdown.

I have tried to insert this code inside the timer:

private void timer2_Tick(object sender, EventArgs e)
{
    string timeOp = dataGridView1.Rows[0].Cells[2].Value + "";
    DateTime timeConvert;
    DateTime dateTime = DateTime.Now;
    DateTime.TryParse(timeOp, out timeConvert);

    double time;
    time = timeConvert.TimeOfDay.TotalMilliseconds;
    var timeSpan = TimeSpan.FromMilliseconds(time);

    if (time > 0)
    {
        time = time - 1000; //(millisec)
        lblCountdown.text = time.ToString();
    }
}

didn't count down or anything, does someone has an idea of what should I do or why it isn't working?


Solution

  • The value of time never changes, because you create it again fresh each time.

    To solve this, you have to declare the variable you decrement outside of the Tick event.

    Put these two variables on your form:

    private int milliSecondsLeft = 0;
    private bool timeSet = false;
    

    Then change the 'tick' event to this:

    private void timer2_Tick(object sender, EventArgs e)
    {
        if (!timeSet) // only get the value once
        {
            string dateTimeFromGrid = "4/29/2016 5:00:00 AM"; //hardcoded for simplicity, get the string from your grid
            DateTime fromGrid;
            DateTime.TryParse(dateTimeFromGrid, out fromGrid);
            milliSecondsLeft = (int)fromGrid.TimeOfDay.TotalMilliseconds;  
            timeSet = true;
        }
    
        milliSecondsLeft = milliSecondsLeft - 100; // timer's default Interval is 100 milliseconds
    
        if (milliSecondsLeft > 0)
        {
            var span = new TimeSpan(0, 0, 0, 0, milliSecondsLeft);
            lblCountdown.Text = span.ToString(@"hh\:mm\:ss");
        }
        else
        {
            timer2.Stop();
        }
    }
    

    Make sure