我该如何在C#中制作一个倒计时计时器,该计时器占小时,分钟和秒?

时间:2019-01-19 09:31:46

标签: c#

我不是一个好的程序员,而是我的爱好。 因此,请不要因为我擅长编程而对我进行判断。这是我当前为倒数计时器编写的代码。

foreach(DataGridViewRow row in grdWorkDayTime.Rows)
            {
                DataGridViewButtonCell btncell = (DataGridViewButtonCell)row.Cells[4]; //Cells[4] is edit button
                btncell.ReadOnly = true;
                row.Cells[5].ReadOnly = true; //Cells[5] is delete button
            }

运行计时器时。那么TextBox1不会显示00:00:01,而是显示100; 00; 00。 感谢您一次又一次地阅读我的文章,对您的编程知识太差感到抱歉。

3 个答案:

答案 0 :(得分:4)

您可以使用此:

TimeSpan time = TimeSpan.FromSeconds(i);
textBox1.Text = time.ToString(@"hh\:mm\:ss");

答案 1 :(得分:0)

好吧,所以您知道如何使用Timer,但是问题出在string上,当您在+上使用string时,您concatenating个,因此说"hello" + " world"等于"hello world",因此当您将i00:00:00并置时,您看到的输出是非常合逻辑的。
您可以使用下面的代码段实现目标(只需将表单类内容替换为此)

private Timer _timer;
private Label _label;
private int _elapsedSeconds;
public Form1()
{
    _timer = new Timer
    {
        Interval = 1000,
        Enabled = true
    };
    _timer.Tick += (sender, args) =>
    {
        _elapsedSeconds++;
        TimeSpan time = TimeSpan.FromSeconds(_elapsedSeconds);
        _label.Text = time.ToString(@"hh\:mm\:ss");
    };

    _label = new Label();

    Controls.Add(_label);
}

编辑

Tnx到@Juliet Wilson我编辑了时间如何转换为字符串

答案 2 :(得分:-1)

我建议为此使用秒表。它将做您需要的魔术。在这里,您可以找到在C#https://www.dotnetperls.com/stopwatch中使用Stopwatch类的良好示例。

相关问题