For
...Next
loop is used for repeating the same action for a finite number of times. The statements inside the following loop will be executed 11 times. The first time, i
will have the value 0, the second time it will have the value 1, the last time it will have the value 10.
For i As Integer = 0 To 10
'Execute the action
Console.Writeline(i.ToString)
Next
Any integer expression can be used to parameterize the loop. It is permitted, but not required, for the control variable (in this case i
) to also be stated after the Next
. It is permitted for the control variable to be declared in advance, rather than within the For
statement.
Dim StartIndex As Integer = 3
Dim EndIndex As Integer = 7
Dim i As Integer
For i = StartIndex To EndIndex - 1
'Execute the action
Console.Writeline(i.ToString)
Next i
Being able to define the Start and End integers allows loops to be created that directly reference other objects, such as:
For i = 0 to DataGridView1.Rows.Count - 1
Console.Writeline(DataGridView1.Rows(i).Cells(0).Value.ToString)
Next
This would then loop through every row in DataGridView1
and perform the action of writing the value of Column 1 to the Console. (The -1 is because the first row of the counted rows would be 1, not 0)
It is also possible to define how the control variable must increment.
For i As Integer = 1 To 10 Step 2
Console.Writeline(i.ToString)
Next
This outputs:
1 3 5 7 9
It is also possible to decrement the control variable (count down).
For i As Integer = 10 To 1 Step -1
Console.Writeline(i.ToString)
Next
This outputs:
10 9 8 7 6 5 4 3 2 1
You should not attempt to use (read or update) the control variable outside the loop.