Arrays in Visual Basic

The next example illustrates an array of colors. The array is declared globally, colors are added in form load. Whenever the user clicks the form the next color is shown. The index is stored in a global variable Num. Each time the user clicks, num is incremented. If Num is larger than the size of the array, Num is set back to 0.
'Illustrate array of colors
Public Class Form1
    'Programmer: Janet Joy
    Dim MyColors(2) As Color 'Global
    Dim Num As Integer 'Global, automatically initialized to 0
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'Initialize array
        MyColors(0) = Color.Red
        MyColors(1) = Color.White
        MyColors(2) = Color.Blue
    End Sub

    Private Sub Form1_MouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
        'Show the next color in array. Go back to 0 at end.
        Num = Num + 1
        If Num > 2 Then Num = 0 'Make sure the subscript is not out of bounds
        Me.BackColor = MyColors(Num)
    End Sub
End Class

Run the program and click to cycle through the colors. Save the program.

Experiment: Add 3 or 4 more colors. Make sure it cycles through all of the colors.

Experiment: Initialize the colors in the declaration and get rid of form load.

Experiment: Add the name of the color:

  Me.BackColor = MyColors(Num)
  Me.Text = MyColors(Num).ToString

NEXT: A lookup example