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.
Public Class Form1
    Dim MyColors(2) As Color 'Global
    Dim Num As Integer 'Global, automatically initialized to 0

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As  _
            System.EventArgs) Handles MyBase.Load
        MyColors(0) = Color.Red
        MyColors(1) = Color.White
        MyColors(2) = Color.Blue
    End Sub 'Form1_Load

    Private Sub Form1_MouseClick(ByVal sender As Object, ByVal e As  _
            System.Windows.Forms.MouseEventArgs) Handles Me.MouseClick
        Num = Num + 1
        If Num > 2 Then Num = 0
        Me.BackColor = MyColors(Num)
    End Sub 'Form1_MouseClick
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

INDEX, Scalar Variables vs. Arrays, Example 1: Initialize, Out of Bounds Exception, Arrays of Objects, Julian Date, ReDim: Change the Size of the Array, No Duplicates, Collections
Next lesson: Strings in Visual Basic

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

Arrays of Objects