如何建立进阶倒数计时器 [英] How to create an advanced countdown timer

查看:94
本文介绍了如何建立进阶倒数计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,这个问题与此相关,所以你们可以更好地理解它。

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

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

我的答案:

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();

根据我在此处写的答案,我想知道是否有一种方法可以应用它计时器,然后将DataGrid值(转换后)转换为计时器值。因此,如果我按下按钮,它们将开始倒计时。

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?

推荐答案

time的值永远不会更改,因为您每次都会重新创建它。

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

要解决此问题,必须在 Tick 事件之外声明要减小的变量。

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;

然后将 tick事件更改为此:

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();
    }
}

请确保

这篇关于如何建立进阶倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆