thisguyAgain thisguyAgain - 1 month ago 10
Vb.net Question

How to update a label control every nTH seconds on winform?

I have a label on my winform that when the form loads, counts how many files are in a directory. I want to update that label every nTH seconds while the winform application is running. I'm not sure how to acheive this, here's my on load to count the files:

Public Function getUserCountsTotal() As Integer
Dim di As New DirectoryInfo("C:\myDirectory")
Dim Users As FileInfo() = di.GetFiles().OrderByDescending(Function(fi) fi.LastWriteTime).ToArray()

Dim user As FileInfo

'list the names of all files in the specified directory
For Each user In Users
ComboBox1.Items.Add(Path.GetFileNameWithoutExtension(user.Name) & "- " & user.LastWriteTime)
Next

getUserCountsTotal = ComboBox1.Items.Count + 1
End Function

Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
statusPanel.Text = ""
statusPanel.Text = "Logged in as " & getYourUserName() & " - " & "[ " & getUserCountsTotal() & " ] "
End Sub

Answer

Put a timer on a form and set the Enabled property to true. Double-click on the timer and enter the code that counts the files in the directory:

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Dim counter = My.Computer.FileSystem.GetFiles("C:\myDirectory")
    Label1.Text = counter.Count
End Sub

You set the interval in Timer's Interval property in milliseconds. To update every two seconds set the value to 2000, to update every three seconds set it to 3000 etc.