2013-07-02 19 views
3

我想在我的程序中插入一個倒計時器insde我的標籤,但是當我運行該程序它不倒計時。它跳到一個,就是這樣。定時器內標籤

Private Sub CompactTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompactTimer.Tick 
    Dim Time As Integer = 11 
    Do Until Time = 0 
     ClockLabel.Text = "Compacting database in: " & Time 
     Time -= 1 
    Loop 
End Sub 

我也啓動了計時器並在Form_Load函數中聲明間隔爲500。

回答

5

擺脫循環並在範圍外聲明Time變量。

Dim Time As Integer = 11 

Private Sub CompactTimer_Tick(ByVal sender As Object, ByVal e As EventArgs) _ 
           Handles CompactTimer.Tick 
    If Time >= 0 Then 
    ClockLabel.Text = "Compacting database in: " & Time 
    Time -= 1 
    Else 
    CompactTimer.Stop 
    End If 
End Sub 
+0

哈哈,這讓我感覺很蠢,謝謝。我不能接受另一個9分鐘的答案,但我會盡我所能。 –

2

每當計時器滴答時發生循環。你最有可能想要的東西,如:

Dim time as Integer = 11 ' Declare outside 
Private Sub CompactTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompactTimer.Tick 
    If Time = 0 Then 
     CompactTimer.Enabled = False ' Disable timer 
     ClockLabel.Text = "Compacting database now" 
    Else 
     ClockLabel.Text = "Compacting database in: " & time 
     time -= 1 
    End If 
End Sub 
3

使靜態無功..

Private Sub CompactTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompactTimer.Tick 
    Static Time As Integer = 11 

    ClockLabel.Text = "Compacting database in: " & Time 
    Time -= 1 
    If Time = 0 Then CompactTimer.Stop 

End Sub 
2

如果你想要的代碼顯示的實際時間量,則代碼看起來是這樣的。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    'start the count down 
    CompactTimer.Interval = 500 
    CompactTimer.Start() 
    stpw.Stop() 
    stpw.Reset() 
    stpw.Restart() 
End Sub 

Dim stpw As New Stopwatch 
Dim countdown As New TimeSpan(0, 0, 11) 'length of countdown in seconds 

Private Sub CompactTimer_Tick(ByVal sender As System.Object, _ 
           ByVal e As System.EventArgs) Handles CompactTimer.Tick 
    Dim togo As TimeSpan = countdown - stpw.Elapsed 
    If togo.TotalSeconds > 0 Then 
     ClockLabel.Text = String.Format("Compacting database in: {0} secs.", togo.TotalSeconds.ToString("n0")) 
    Else 
     CompactTimer.Stop() 
    End If 
End Sub 

依靠標記時間間隔的間隔會導致不準確。