Looping through an array

Review the note on arrays with variable subscripts before this note.

We often use loops to process data in an array, as illustrated in this program:

    Dim strNames(9) As String
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        strNames(0) = "George Washington"
        strNames(1) = "Martha Washington"
        strNames(2) = "Abraham Lincoln"
        strNames(3) = "Mary Lincoln"
        strNames(4) = "John F. Kennedy"
        strNames(5) = "Jacqueline Kennedy"
        strNames(6) = "Dwight D. Eisenhower"
        strNames(7) = "Mamie Eisenhower"
        strNames(8) = "Harry Truman"
        strNames(9) = "Bess Truman"
    End Sub
    Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
        Dim i As Integer
        txtOut.Text = ""
        For i = 0 To 9
            txtOut.AppendText(strNames(i) & vbCrLf)
        Next
    End Sub
    Private Sub btnFirst_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFirst.Click
        txtOut.Text = strNames(0)
    End Sub
    Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
        txtOut.Text = ""
    End Sub
The FormLoad event handler initializes the array called strNames.

The event handler for clicking on btnDisplay loops through the array, displaying one element in each iteration. The loop index is used as a subscript, so it automatically advances from one element to the next with each iteration. It might be helpful to you to think of the index variable as pointing to each element as it steps through the array.

The btnFirst event handler displays the first element in the array (the one with a subscript of 0) and the btnClear event handler clears the display.