Tuesday, February 5, 2008

Simple Progress Bar vb.net Code

Here is a simple sample of using a progress bar in vb.net 2005:

I have a form with a progress bar on it called progBar1, a button called btnUpgrade, and a backgroundworker called bwBackgroundWorker.




Private Sub btnUpgrade_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpgrade.Click


        Try


            '//Disable the upgrade button


            Me.btnUpgrade.Enabled = False


 


            '//Create a new instance and initialize


            bwBackgroundWorker = New System.ComponentModel.BackgroundWorker


            bwBackgroundWorker.WorkerReportsProgress = True


            bwBackgroundWorker.WorkerSupportsCancellation = True


            bwBackgroundWorker.RunWorkerAsync()


 


        Catch ex As Exception


            RptError("Unable to upgrade!", ex)


        End Try


    End Sub


 


    Private Sub bwBackgroundWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwBackgroundWorker.DoWork


        '//Just for a test, create a loop


 


        For X As Int32 = 0 To 100


            If bwBackgroundWorker.CancellationPending Then


                Exit For


            End If


 


            bwBackgroundWorker.ReportProgress(X)


            Threading.Thread.Sleep(100)


        Next


    End Sub


 


    '//Update the progress bar


    Private Sub bwBackgroundWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwBackgroundWorker.ProgressChanged


        Me.progBar1.Value = e.ProgressPercentage


    End Sub


No comments: