Home > Mobile >  VB Showing progress in a Label on Form1
VB Showing progress in a Label on Form1

Time:08-02

I have a Form1 with a "Rename" button: btnRename.
On Form1 I also have a label: lblProgress

Private Sub btnRename_Click(sender As Object, e As EventArgs) Handles btnRename.Click
    Call Do_Rename()
    Me.Close()
End Sub

Private Sub Do_Rename()
    Call Get_File_names()
    digits = 5
    lblProgress.Text = "1 of 15"
    Call Renumbering()
End Sub

When I click on the "Rename" button I want

  • to do some file renaming
  • to show progress like:
    • 1 of 18
    • 5 of 18
    • 10 of 18
    • 15 of 18

When I set: lblProgress.Text = "1 of 18", nothing shows up on the form!

CodePudding user response:

You should do the following:

  1. Create a BackgroundWorker
  2. Call RunWorkerAsync in the button's click event
  3. In the DoWork event of the BackgroundWorker, loop over the files to do your file renaming
  4. Call ReportProgress in the loop based on the currently iterated file
  5. In the ProgressChanged event of the BackgroundWorker, update the label's text based on the data sent back from the ReportProgress method

Example:

Private Sub btnRename_Click(sender As Object, e As EventArgs) Handles btnRename.Click
    BackgroundWorker1.RunWorkerAsync()
End Sub

Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    Dim worker = DirectCast(sender, BackgroundWorker)
 
    For i = 0 To files.Count - 1
        worker.ReportProgress(i, $"{i   1} of {files.Count}")
 
        ' do your opeations on files
    Next
End Sub
 
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
    lblProgress.Text = e.UserState.ToString()
End Sub
 
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
    lblProgress.Text = "BackgroundWorker completed."
End Sub

CodePudding user response:

Add Doevents or Application.DoEvents() before and after change the label text or you can follow BackgroundWorker as mention by David.

Private Sub Do_Rename()
Call Get_File_names()
Application.DoEvents()
digits = 5
lblProgress.Text = "1 of 15"
Application.DoEvents()
Call Renumbering()
End Sub
  • Related