Looping through an Array in ASP.NET / VB.NET

In our example code below we create a string array 'myArray'. The Ubound function returns the 'index' of the highest element in an array. So we use a For Next loop and our counter variable iCounter, and loop through the array from 0 (the starting index) to the highest element, in this example 3 and add the values of each element to our string ‘myString’.

We then set the text property of the literal control ‘ltlArray’ to the value of ‘myString’.

The first element in our array has a starting index of 0, so our example array has 4 elements. The first element holds the value ‘BMW’ and so on.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

       Dim myString As String
       Dim iCounter As Integer   

        myString = ""
        iCounter = 0

        Dim myArray() As String

        myArray = New String() {"BMW", "Mercedes", "Honda", "Porshe"}

        For iCounter = 0 To UBound(myArray) 'in this example loop through 0 to 3

            myString = myString & myArray(iCounter) & "<br />"

        Next

        ltlArray.Text = myString

    End Sub

</script>

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Arrays in ASP.NET</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <asp:Literal ID="ltlArray" runat="server" />

    </div>

    </form>

</body>

</html>

Alternatively you could iterate through an array like this using the For Each Loop and print it out on a web page.

Dim myArray() As String

myArray = New String() {"BMW", "Mercedes", "Honda", "Porshe"}

Dim myString As String

For Each myString in MyArray
Response.Write(myString)
Next

In Part 1 learn the basics of Arrays in ASP.NET
In Part 2 learn how to Reference an Array Element
In Part 3 learn how to Loop through an array in ASP.NET and VB.NET

Advertisements



MembersPro

MembersPro PayPal - ASP Membership software

Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.

Get your best asp web hosting provider now and save 25%