0
votes

Windows Forms, VB application... Forgive me in advance for this very elementary question but I am overlooking something really simple here. I would like to have a label show the current value of a variable as the for each loop runs.. I created a very simple Button Click event to figure out where its failing. As it is right now the value does not display until after the for each loop finishes running, which it should actually display the counter value each time it runs through... I know this is possible and really simple because I did it years back but for the life of me cant figure out why I am missing the bar as it should constantly update the label to reflect that? Test Sub is as follows:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim counter As Integer = 0
    For x As Integer = 1 To 200000
        counter += 1
        Label1.Text = Convert.ToString(counter)
    Next
End Sub
2
Add Label1.Update(). That will work for about 5 seconds until Windows puts a stop to it. - Hans Passant

2 Answers

5
votes

Try adding the line: Application.DoEvents() inside the loop.

1
votes

try this

For x As Integer = 1 To 200000
    counter += 1
    Label1.Text = Convert.ToString(counter)
    System.Threading.Sleep(200)
Next

I would advise you to use BackGroundWorker if you want to have a report progres.

SEE HERE
SEE ALSO HERE
BEST LINK for me and this