How to create an advanced countdown timer

痞子三分冷 提交于 2019-12-25 17:34:06

问题


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

  • How to convert the "time" from DateTime into int?

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?


回答1:


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



来源:https://stackoverflow.com/questions/36943993/how-to-create-an-advanced-countdown-timer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!