Arrays in Visual Basic

In the lesson on loops you saw the For Each loop used to align the controls on the form. A collection is very similar to an array, but has a few more methods.

Instead of all of the controls on the form, we can also create our own collection,

Create a new windows form application.

Add a label called Label1, two checkboxes named CheckBox1 and CheckBox2.

Writew the code as shown below:

'Creating a collection
Public Class Form1
    'Programmer: Janet Joy
    Dim MyCollection As Collection = New Collection()
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'Add all controls to collection, then change backcolor of all
        MyCollection.Add(Me.Label1, "one")
        MyCollection.Add(Me.CheckBox1, "two")
        MyCollection.Add(Me.CheckBox2)
        For Each ctrl As Control In MyCollection
            ctrl.BackColor = Color.DarkKhaki
        Next
        MyCollection.Item("one").backcolor = Color.Red
        MyCollection.Remove("one")
        Me.Text = MyCollection("two").text 'displays "checkbox1"
        MyCollection.Clear() 'remove all items
    End Sub
End Class

One advantage of a collection is that the key can be used instead of an index.

NEXT: Strings in Visual Basic