How to use ProgressBar in VB.NET correctly

I need to use the progress bar in my VB.NET programs, which is very different from those found in VB6. For example, if I have a procedure to populate a datagridview through some loop and show that progress with progressbar, what happened?
Datagridview fills 100% and progress up to 50%!

Here is an example program to illustrate the problem. Create a new project, add a window form and simply copy this code in the code of Form1.

Public Class Form1 Dim myMax As Integer = 100000 Dim pb As New ProgressBar Dim dgv As New DataGridView Dim WithEvents ti As New Timer Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load With Me .Width = 400 .Height = 250 .Controls.Add(pb) With pb .Maximum = myMax .Dock = DockStyle.Bottom End With .Controls.Add(dgv) With dgv .ColumnCount = 2 .Dock = DockStyle.Fill .Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill .Visible = False End With End With ti.Start() End Sub Private Sub OnFormLoaded(ByVal sender As Object, ByVal e As EventArgs) Handles ti.Tick ti.Enabled = False ti.Dispose() Dim temp As Integer For t = 0 To myMax If t Mod 100 = 0 Then pb.Value = t pb.Refresh() Application.DoEvents() temp += 1 dgv.Rows.Add(New String() { _ t.ToString, _ temp.ToString _ }) End If Next pb.Value = myMax pb.Visible = False dgv.Visible = True dgv.Focus() End Sub End Class 

This code creates several controls, loads a form and starts a cycle to fill in the data and shows the progress in the progress bar. After that, the program hides the progress indicator and shows a datagridview, which usually happens in specific (real) programs.

The problem is that although both options, populating and updating the datagridview control panel come from the same cycle (step by step 100), populating the datagridview ends much faster than the progressbar shows progress and hides it by about 50%.

This is very different from VB6, where the fill and display are fully synchronized, and the grid will be shown after the progress indicator reaches 100%.

How to get such progressbar functionality in VB.NET on the code shown?
I am trying to update progressbar and DoEvents, but this is not enough to make it work properly.

+4
source share
1 answer

To solve this problem without performing the “threaded science fiction” from ProgressBar only, you need to use one method, which is often used with microsoft GUI tools.

This approach could probably solve your specific problem:

  If t Mod 100 = 0 Then pb.Value = t If pb.Value > 0 Then pb.Value -= 1 temp += 1 dgv.Rows.Add(New String() { _ t.ToString, _ temp.ToString _ }) End If 
+2
source

All Articles