Search code examples
vb.netvisual-studio-2010timertextbox

Refreshing text in a TextBox at intervals of 1 second


I am attempting to display the local time in a text box but have it refresh... I used a timer to hopefully refresh the time, but it does not seem to reprint my text. If you could take the time to help me out that would be great!

EDIT*** So I attempted this with TextBox.AppendText() to see what happens if it continually reprints and I noticed that the date and time does not update at all. Do I need to refresh the form???

Public Class Form1

    Dim t As String = My.Computer.Clock.LocalTime
    Dim m As String = t & vbCrLf & " - Time Left - "
    Private Timer As System.Windows.Forms.Timer
    Private TimerCounter As Integer = 0
    Dim TempText As String = m

    Protected Sub TimerTick(ByVal sender As Object, ByVal e As EventArgs)
        TextBox.TextAlign = HorizontalAlignment.Center
        TimerCounter += 1
        TextBox.Text = t
    End Sub

    Private Sub Form1_Shown(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Shown 'this goes with the line just above
        Timer = New Windows.Forms.Timer With {.Interval = 1000}
        AddHandler Timer.Tick, AddressOf TimerTick
        Timer.Start()
    End Sub

End Class

My expected result if for the local time to update in the textbox1 each time the timer ticks.


Solution

  • You set the variable t at the moment of its declaration, but then you never update it. So it contains always the same value.
    In reality you don't even need that variable. You can set simply the TextBox.Text to the My.Computer.Clock.LocalTime

    Protected Sub TimerTick(ByVal sender As Object, ByVal e As EventArgs)
    
        ' You can set this property just one time when you define your TextBox
        ' TextBox.TextAlign = HorizontalAlignment.Center
        TimerCounter += 1
        TextBox.Text = My.Computer.Clock.LocalTime
    End Sub