Kat
Kat

Reputation: 2500

Progress bar not showing fill (vb.net/Visual Studio)

I have a code set up that will loop around and perform some network firmware functions. For the user, I have a progress bar form that pops up and shows them the status as it happens. The code is pretty straight forward:

 ProgressBar.Show()

 For j As Integer = 0 To datagridview.Rows.Count - 1

 'do network functions

 ProgressBar.ProgressBar1.Increment(100 / (datagridview.Rows.Count))

 next

 ProgressBar.Close()

ProgressBar is the name of the form with the progressbar on top of it. It's a very simple form. So if I put a break point at the "for" line, i.e. j = 0, I get my progress bar looking like this: enter image description here

Well, that gives no info. If I step to the point of the incrementing line below, it shows! enter image description here

I thought that if I add some progressbar increment earlier, that the bar would fill. So I tried that. So here's what I changed it to:

 ProgressBar.Show()

 ProgressBar.ProgressBar1.Increment(100 / (datagridview.Rows.Count+1))

 For j As Integer = 0 To datagridview.Rows.Count - 1

 'do network functions

 ProgressBar.ProgressBar1.Increment(100 / (datagridview.Rows.Count+1))

 next


ProgressBar.Close()

Yet if I stop at the for loop in a break point, I still have a white bar instead of a green filled one. What am I doing wrong? I feel that this is something simple/noob level. Appreciated.

Upvotes: 1

Views: 6418

Answers (1)

TimG
TimG

Reputation: 602

@Hans Passant's comment is correct. Your UI thread is stuck. It is waiting for your background thread (ie, your looping code) to finish before it repaints the screen.
When I use a progress bar, I put a DoEvents() call in the loop, like this:

ProgressBar.Show()

ProgressBar.ProgressBar1.Increment(100 / (datagridview.Rows.Count+1))

For j As Integer = 0 To datagridview.Rows.Count - 1
   'do network functions
   ProgressBar.ProgressBar1.Increment(100 / (datagridview.Rows.Count+1))
   'force .NET to update the forground thread, so the progress bar looks like it should
   Application.DoEvents()
Next

ProgressBar.Close()

The call to DoEvents, essentially halts the background execution until the UI has time to update, and then continues the background execution.

Upvotes: 2

Related Questions