Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

ASP.NET Razor VB loops and arrays


May 12, 2021 ASP.NET


Table of contents


ASP.NET Razor - VB loops and arrays

Razor ASP.NET VB (Visual Basic), and this section describes how convenient it is to repeat the same statement.

Statements are repeated in a loop.


For loop

If you need to repeat the same statement, you can set a loop.

If you know how many times you want to loop, you can use for loops. This type of loop is especially useful when counting up or down:

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

Run an instance . . .


For Each loop

If you're using a collection or array, you'll often use the for each loop.

A collection is a similar set of objects, and the for each loop can traverse the collection until it is complete.

In the following example, traversing ASP.NET request.ServerVariables collection.

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

Run an instance . . .


While loop

The while loop is a generic loop.

The while loop starts with the while keyword, followed by parentheses, in which you can specify how long the loop will last, followed by a block of code that repeats.

While loops typically set an incremental or decreasing variable to count.

In the following example, the operator adds 1 to the value of variable i for each loop.

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

</body>
</html>

Run an instance . . .


Array

When you want to store multiple similar variables but don't want to create a separate variable for each variable, you can use arrays to store:

@Code
Dim members As String()={"Jani","Hege","Kai","Jim"}
i=Array.IndexOf(members,"Kai")+1
len=members.Length
x=members(2-1)
end Code
<html>
<body>
<h3>Members</h3>
@For Each person In members
@<p>@person</p>
Next person

<p>The number of names in Members are @len </p>
<p>The person at position 2 is @x </p>
<p>Kai is now in position @i </p>
</body>
</html>

Run an instance . . .