Visual Basic For Next
The For Next loop (or For Iteration) loops through data and can be very useful when looping through lists.
Syntax
For index = 1 To 10 Next
We will perform a small loop, printing the numbers 1 to 50 on the screen.
For i = 1 To 50 Console.WriteLine(i) Next Console.ReadLine()
When you debug this, you should see it print out 1 to 50 on the screen.
Using Step Keyword
In the above example, the numbers print out from 1 to 50 incremented by 1 each time. However, by using the step keyword you can increment by 3, 7, 8 or any other number each time.
Example
For myNumber As Integer = 1 To 50 Step 5 Console.WriteLine(myNumber) Next Console.ReadLine()
We do two things in this example: First we declare a variable called myNumber and set the data type as integer, but without using the Dim keyword. Instead, we use the For keyword to make the variable, that means this variable is local to this For Loop Statement. This is an Inline Variable. Next we print out 1 to 50, but we increment by 5 each time.
Looping Backwards
You can also loop backwards, similar to the example above.
Example
For myNumber As Integer = 50 To 1 Step -5 Console.WriteLine(myNumber) Next Console.ReadLine()
This time we are going backwards; notice how we have put a negative sign in front of the 5. As a result, the numbers 50, 45 40… should print out.
You can print out any kind of information, not just numbers, such as words or other data. A good example of this is when filling out online forms, and you get a drop-down list asking you to select the year. This is done server side, where they use one piece of code like the one above.
Example – Get System Fonts
Before we begin, you must reference the System.Drawing.Text above Module put this:
Imports System.Drawing.Text
In the solution explorer, right click on your project name and click on Add Reference. Ensure you have selected Framework on the left hand side (if using VS 2012), and make sure System.Drawing.Text is ticked. Now copy this:
Dim fonts As New InstalledFontCollection() For fntFamily As Integer = 0 To fonts.Families.Length - 1 Console.WriteLine(fonts.Families(fntFamily).Name) Next Console.ReadLine()
This will print out all the fonts to the console.
Summary
This tutorial addressed the For Next Loop, and we learned how to use the step keyword and loop backwards. For Statements are useful for printing out large amounts of data such as years, days, and months.