简体   繁体   English

如何建立进阶倒数计时器

[英]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. 根据我在此处写的答案,我想知道是否可以将其应用于计时器并将DataGrid值(转换后)转换为计时器值。 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? 没有倒数或其他任何事情,有人知道我应该做什么或为什么不起作用吗?

The value of time never changes, because you create it again fresh each time. time的价值永远不会改变,因为您每次都会重新创建它。

To solve this, you have to declare the variable you decrement outside of the Tick event. 为了解决这个问题,您必须在Tick事件之外声明要减少的变量。

Put these two variables on your form: 将这两个变量放在表单上:

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

Then change the 'tick' event to this: 然后将“ tick”事件更改为此:

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 确保

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM