Looping for Dummies

Ahh, so I just had a revisit of why For loops are not as good as While loops sometimes. Most commonly, I try to avoid using While loops, but after trying to convert this Master Detail example I realized that I needed a While loop instead of a For loop.

Why? Well, if you look at that example, it shows that it is using a post processing incrementor, and well, VB.NET doesn't have this. So, I had to come up with the same basic functionality, but it posed definate problems because it wasn't going through all of the rows in the DataGrid.

My first attempt created a variable for the upper bound item which I had to go to, however this variable had to be modified when a new row was added (so it would get to all of the rows). Well, after playing with it for awhile, I realized that when using a For loop, you cannot increment that upper bound variable and have it applied on the fly. The For loop takes whatever it is and stores the value and not the reference to the variable.

Ahh - so this is where the While loop comes in. After changing the loop to it, I was able to increment my upper bound variable and gain access to all of the rows in the datagrid.

So remember:

Dim i As Integer
Dim j As Integer = 10

For i = 0 To j
  If somethingIsTrue Then
    i += 1
    j += 1
  End If
Next

will not work, but:

Dim i As Integer = 0
Dim j As Integer = 10

While i <= j
  If somethingIsTrue Then
    i += 1
    j += 1
  End If
  i += 1
End While

Will work!

No Comments