Countdown after clicking a button that goes from 10 to 0 setting text on a label C#

*爱你&永不变心* 提交于 2019-12-01 23:24:06

Using WindowsFormsApplication u can do it like this:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        timer1.Enabled = false; // Wait for start
        timer1.Interval = 1000; // Second
        i = 10; // Set CountDown Maximum
        label1.Text = "CountDown: " + i; // Show
        button1.Text = "Start";
    }

    public int i;

    private void button1_Click(object sender, EventArgs e)
    {
        // Switch Timer On/Off
        if (timer1.Enabled == true)
        { timer1.Enabled = false; button1.Text = "Start"; }
        else if (timer1.Enabled == false)
        { timer1.Enabled = true; button1.Text = "Stop"; }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (i > 0)
        {
            i = i - 1;
            label1.Text = "CountDown: " + i;
        }
        else 
        { timer1.Enabled = false; button1.Text = "Start"; }
    }
}

You only need a label, a button and a timer.

It sounds like you probably just need three things:

  • A counter in your class as an instance variable
  • A timer (System.Windows.Forms.Timer or a DispatcherTimer depending on what UI framework you're using)
  • A method handling the timer's Tick even which decrements the counter, updates the UI, and stops the timer + takes a snapshot if the counter reaches 0

You can do all of this without any other threads.

use this code. put one timer,label and button.

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
        timer1.Tick += new EventHandler(timer1_Tick);
    }
    private static int i = 10;
    private void button1_Click(object sender, EventArgs e)
    {
        label1.Text = "10";
        timer1.Interval = 1000;
        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        label1.Text = (i--).ToString();
        if (i < 0)
        {
            timer1.Stop();
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!