<Previous lesson | Table of Content | Content of this Chapter | Next lesson>

VB Collection Object

Visual Basic has an object name Collection, an ordered set of items that can be referred to as a unit. Compare to Array which each member should have the same data type, member or item in the collection does not need to have the same data type. Usually you use collection object when you want to store many objects or different types of variables into one unit.

Collection has three methods and one property:
Add (Item, Key, Before, After) method: adds items to the collection
Item (Index) method: return an item by index or by key
Remove (Index) method: delete item from collection by index or by key
Count property: return the number of items in the Collection

To use a collection, we need to declare collection variables
Example: Dim myCollection as New Collection

Project: Collection Example
We are going to use collection object to represent district data of population
1. Open a new standard Exe VB project
2. In the project window, right click and Add > Class Module then press Open button.
3. Type the following code in the Class1 to hold the name of each instance/object of Class1:

Public InstanceName

4. The following code is from MSDN VB help. Copy and paste it in the declaration section of Form1:

Sub ClassNamer()
Dim MyClasses As New Collection ' Create a Collection object.
Dim Num ' Counter for individualizing keys.
Dim Msg As String ' Variable to hold prompt string.
Dim TheName, MyObject, NameList ' Variants to hold information.
Dim Inst As New Class1 ' Create a new instance of Class1.
Num = Num + 1 ' Increment Num, then get a name.
Msg = "Please enter a name for this object." & Chr(13) _
& "Press Cancel to see names in collection."
TheName = InputBox(Msg, "Name the Collection Items")
Inst.InstanceName = TheName ' Put name in object instance.
' If user entered name, add it to the collection.
If Inst.InstanceName <> "" Then
' Add the named object to the collection.
MyClasses.Add Item:=Inst, Key:=CStr(Num)
End If
' Clear the current reference in preparation for next one.
Set Inst = Nothing
Loop Until TheName = ""
For Each MyObject In MyClasses ' Create list of names.
NameList = NameList & MyObject.InstanceName & Chr(13)
Next MyObject
' Display the list of names in a message box.
MsgBox NameList, , "Instance Names In MyClasses Collection"

For Num = 1 To MyClasses.Count ' Remove name from the collection.
MyClasses.Remove 1 ' Since collections are reindexed
' automatically, remove the first
Next ' member on each iteration.
End Sub

5. To call the procedure above, you type the name of the procedure in Form_click event procedure:

Private Sub Form_Click()
End Sub

6. Run the program, and click cancel to see the list. Use F8 key repetitively to trace the values and to see how it works.


<Previous lesson | Table of Content | Content of this Chapter | Next lesson>