Arrays in Visual Basic

The next example illustrates using a combo box to lookup information.

  1. Create a new VB project.
  2. Add a combo boxComboBox, name it CboColors.

color lookup

We have 3 arrays: English, Spanish and MyColors. In form load all of the elements in English are added to the combo box. When a color is selected from the combo box, we use the combo box's selectedIndex to display the name of the color in Spanish and change the background color of the form.

'Array of colors
Public Class Form1
    'Programmer: Janet Joy
    Dim English() As String = {"red", "yellow", "blue", "green"}
    Dim Spanish() As String = {"rojo", "amarillo", "azul", "verde"}
    Dim MyColors() As Color = {Color.Red, Color.Yellow, Color.Blue, Color.Green}
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'At form load add the names of colors in English to combo box
        Dim num As Integer
        Me.CboColor.Text = "Select a color"
        For num = 0 To English.Length - 1
    End Sub

    Private Sub CboColors_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CboColor.SelectedIndexChanged
        'When the user selects an itme in combo box, show the color and Spanish word
        Dim num As Integer = CboColor.SelectedIndex
        Me.Text = Spanish(num)
        Me.BackColor = MyColors(num)
    End Sub
End Class

Run the program and select each color. Save the program.

Experiment: Add 3 or 4 more colors. Make sure that each of the colors works correctly.

Experiment: Add a label to display the color.

NEXT: Julian Date