简体   繁体   中英

Multiple countdown timer + button

NOTE: This question is related to this one as well

I have a timer which is activated by a button that starts the countdown of the supposed activity. But I have a problem, when I press the same button again, the program must use another time (specified inside a datagrid) and start the countdown again, and if I press the button again, another time and so on.

Shall I use multiple timers or is there a way I can use the same timer, but with new ("reset") values if I press the button?

(If you guys want me to show more of the code, just tell me I'll post here)

private bool timeSet2 = false;
int f = 1;
private void timer3_Tick(object sender, EventArgs e)
{

    DateTime timeConvert;
    DateTime dateTime = DateTime.Now;

    string timeOp = dataGridView1.Rows[f].Cells[2].Value + "";
    f++;

    if (!timeSet2) // only get the value once
    {
        DateTime.TryParse(timeOp, out timeConvert);
        milliSecondsLeft = (int)timeConvert.TimeOfDay.TotalMilliseconds;
        timeSet2 = true;
    }

    milliSecondsLeft = milliSecondsLeft - 1000;

    if (milliSecondsLeft > 0)
    {
        var span = new TimeSpan(0, 0, 0, 0, milliSecondsLeft);
        lblLeft.Text = span.ToString(@"hh\:mm\:ss");
    }
    else
    {
        timer3.Stop();
    }

I need to fit a button right here so if I press it, my program will start another countdown. But I don't know if I'll have to create another time for this.

You can use the same timer and reset it for each countdown. But I think you are misunderstanding the the functionality of the timer. The timer_Tick event occurs every time the interval of the timer has elapsed. Update the milliSecondsLeft variable on your button click event.

You have to move some code to the button_Click event.

private void button1_Click(object sender, EventArgs e)
{
    milliSecondsLeft = Convert.ToInt32(dataGridView1.Rows[f].Cells[2].Value)*1000;
    f++;
    timer3.Start();
}

Your timer_Tick event would then look like:

private void timer3_Tick(object sender, EventArgs e)
{
    milliSecondsLeft = milliSecondsLeft - 1000;
    if (milliSecondsLeft > 0)
    {
        var span = new TimeSpan(0, 0, 0, 0, milliSecondsLeft);
        lblLeft.Text = span.ToString(@"hh\:mm\:ss");
    }
    else
    {
        timer3.Stop();
    }
}

Some other things:

  • Are you sure you want to start with the second column of your dataGridView with int f = 1;
  • I did not understand your time conversion so I changed it. Now it expects the countdown time in your dataGridView to be in seconds. But perhaps your code is right for your purpose

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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