A collection is very similar to an array, but has a few more methods. We can create an array as shown below. A few controls are placed on the form. Each control on the form can be accessed using
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim myControl As Control
Dim Y As Integer
For Each myControl In Me.Controls
myControl.SetBounds(0, Y, myControl.Width, myControl.Height)
Y += myControl.Height + 10
Next myControl
End Sub 'Form1_Load
We can also create our own collection as shown below:
Public Class Form1
Dim MyCollection As Collection = New Collection()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
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.