I am currently making a timer for a school project. Im a little new to VB.net and having a few problems getting the timer to work.

When the countdown timer gets to 0 the "-" sign appears in the wrong place. As in i get 0:-1

I would also like the text in the timer to turn red when it enters negative numbers. (Maybe Flash, but i guess that is very complicated).

Anyway here is my current code:


Public Class Form1
Inherits System.Windows.Forms.Form
Dim TargetTime As System.DateTime
Dim willy As Integer

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
willy = TextBox1.Text
If Timer1.Enabled Then
Timer1.Stop()
Else
TargetTime = Now.AddMinutes(willy)
Timer1.Start()
End If
Catch ex As Exception
MsgBox("No Time Set")
End Try
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim Diff As TimeSpan = TargetTime.Subtract(Now)
Label1.Text = Diff.Minutes & ":" & Diff.Seconds
End Sub

I'm assuming you are trying to get an output of -0:1...etc..etc...?

Try wrapping the difference in Math.abs() and then concatenating a '-' at the if the output is negative.

Try this:

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Dim Diff As TimeSpan = TargetTime.Subtract(Now)
        If Diff.Seconds < 0 Then
            Label1.Text = "-" & Format(Diff.Minutes, "#0") & ":" & Format(System.Math.Abs(Diff.Seconds), "00")
        Else
            Label1.Text = Format(Diff.Minutes, "#0") & ":" & Format(System.Math.Abs(Diff.Seconds), "00")
        End If
    End Sub

Thanks alot wayne, that worked a treat.

Any idea on how to get the label text to turn red in negatives?

tried loads of different things but none seem to work :(

ok now im using the code that wayne posted, but the minus's arnt quite working properly. with waynes code it works for -0:01 to -0:59 but goes to --01:01. Any suggestions?

Try this:

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Dim Diff As TimeSpan = TargetTime.Subtract(Now)
        If Diff.Seconds < 0 And Diff.Minutes >= 0 Then
            Label1.Text = "-" & Format(Diff.Minutes, "#0") & ":" & Format(System.Math.Abs(Diff.Seconds), "00")
        Else
            Label1.Text = Format(Diff.Minutes, "#0") & ":" & Format(System.Math.Abs(Diff.Seconds), "00")
        End If
    End Sub

Sorry it took so long in replying.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.