Easy Tutorial
❮ Webpages Objects Aspnet Examples ❯

ASP.NET Razor - VB Loops and Arrays


Statements are repeatedly executed within a loop.


For Loop

If you need to execute the same statements repeatedly, you can set up a loop.

If you know the number of times you want to loop, you can use a for loop. This type of loop is particularly useful when counting up or down:

Example

@For i = 10 To 21
    @<p>Line #@i</p>
Next i

For Each Loop

If you are working with a collection or array, you will often use a for each loop.

A collection is a group of similar objects, and a for each loop can iterate through the collection until it is completed.

In the following example, the ASP.NET Request.ServerVariables collection is iterated through.

Example

@For Each x In Request.ServerVariables
    @<li>@x</li>
Next x

While Loop

A while loop is a general-purpose loop.

A while loop starts with the while keyword, followed by parentheses where you can specify how long the loop will continue, and then the block of code to be repeated.

A while loop usually sets an incrementing or decrementing variable for counting.

In the following example, the += operator increments the value of variable i by 1 each time the loop executes.

Example

@Code
Dim i = 0
Do While i < 5
    i += 1
    @<p>Line #@i</p>
Loop
End Code

Arrays

When you need to store multiple similar variables but do not want to create a separate variable for each, you can use an array to store them:

Example

@Code
Dim members As String() = {"Jani", "Hege", "Kai", "Jim"}
i = Array.IndexOf(members, "Kai") + 1
len = members.Length
x = members(2 - 1)
End Code
@For Each person In members
    @<p>@person</p>
Next person
@<p>@len</p>
@<p>@x</p>
@<p>@i</p>
❮ Webpages Objects Aspnet Examples ❯