ArbenM
ArbenM

Reputation: 47

VB.NET Change progressbar value from BackgroundWorker?

I have 2 progress-bars. Now I do some other things in my code, which takes time to execute thus the need to use a backgroundworker. I don't have much of an idea how to use backgroundworker. The rest of my code that I haven't included here executes just fine, but the progressbar values does not change, nor their texts. How would I achieve that?

Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

    Dim LM As RegistryKey = Registry.LocalMachine
    Dim LM_SW As RegistryKey = LM.OpenSubKey("Software")
    Dim LM_MS As RegistryKey = LM_SW.OpenSubKey("Microsoft")
    Dim LM_Win As RegistryKey = LM_MS.OpenSubKey("Windows")
    Dim LM_CV As RegistryKey = LM_Win.OpenSubKey("CurrentVersion")
    Dim AppPaths As RegistryKey = LM_CV.OpenSubKey("App Paths")
    Dim NrOfFiles1 As Integer = AppPaths.SubKeyCount

    ProgressBar2.Maximum = NrOfFiles1
    ProgressBar1.Maximum = 100

    For Each FormatString As String In AppPaths.GetSubKeyNames()
        ProgressBar2.Value += 1 / NrOfFiles1
        ProgressBar1.Value += 1 * ProgressBar2.Value / 100 / 10
        ProgressBar1.Text = ProgressBar1.Value & "%"
        ProgressBar2.Text = ProgressBar2.Value & "%"
    Next

    ProgressBar2.Value = 0

End Sub

Upvotes: 0

Views: 5567

Answers (1)

pinkfloydx33
pinkfloydx33

Reputation: 12739

Use the ProgressChanged event of the Backgroundworker. In your DoWork method, call

BackgroundWorker1.ReportProgress(Percentage) 

Where Percentage is an integer value

Then in the ProgressChanged event you can manipulate your progress bar.

Private Sub backgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As DoWorkEventArgs) Handles backgroundWorker1.DoWork

     Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)

     '''YOUR OTHER CODE
     worker.ReportProgress(PERCENTAGE)
     '''YOUR OTHER CODE

    End Sub 

    ' This event handler updates the progress. 
    Private Sub backgroundWorker1_ProgressChanged(ByVal sender As System.Object,         ByVal e As ProgressChangedEventArgs) Handles backgroundWorker1.ProgressChanged
        ProgressBar1.Text = e.ProgressPercentage.ToString() & "%"
        ProgressBar1.Value  = e.ProgressPercentage
    End Sub 

Upvotes: 2

Related Questions