2011-05-31 2 views
7

J'ai un lblCountdown avec une valeur int de 60. Je veux rendre la valeur int de la diminution lblCountDown avec les secondes jusqu'à ce qu'il atteigne 0.secondes Countdown Timer

C'est ce que j'ai jusqu'à présent:

private int counter = 60; 
    private void button1_Click(object sender, EventArgs e) 
    { 
     int counter = 60; 
     timer1 = new Timer(); 
     timer1.Tick += new EventHandler(timer1_Tick); 
     timer1.Interval = 1000; // 1 second 
     timer1.Start(); 
     label1.Text = counter.ToString(); 
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     counter--; 
     if (counter == 0) 

      timer1.Stop(); 
      label1.Text = counter.ToString(); 

    } 

Répondre

13

Utilisez la minuterie pour cette

private System.Windows.Forms.Timer timer1; 
    private int counter = 60; 
    private void btnStart_Click_1(object sender, EventArgs e) 
    { 
     timer1 = new System.Windows.Forms.Timer(); 
     timer1.Tick += new EventHandler(timer1_Tick); 
     timer1.Interval = 1000; // 1 second 
     timer1.Start(); 
     lblCountDown.Text = counter.ToString(); 
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     counter--; 
     if (counter == 0) 
      timer1.Stop(); 
     lblCountDown.Text = counter.ToString(); 
    } 
+0

timer1 timer pivate? – Kade

+0

vous avez besoin de public? – Stecya

+0

Je ne suis pas sûr de m'aider à vérifier mon code – Kade

0

Une classe publique doit être initialisée pour Form1.

Voir ce code:

namespace TimerApp 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private int counter = 60; 
     private void button1_Click(object sender, EventArgs e) 
     { 
      //Insert your code from before 
     } 

     private void timer1_Tick(object sender, EventArgs e) 
     { 
      //Again insert your code 
     } 
    } 
} 

J'ai essayé et tout a bien fonctionné

Si vous avez plus besoin de l'aide ne hésitez pas à commenter :)

3
int segundo = 0; 
DateTime dt = new DateTime(); 

private void timer1_Tick(object sender, EventArgs e){ 
    segundo++; 
    label1.Text = dt.AddSeconds(segundo).ToString("HH:mm:ss"); 
}