Collection [Part 1] in Visual Basic 6


Collections are objects in Visual Basic that are used to store a group of data values. Collections are similar to array. But there are some special features that differentiate the collections from arrays. 


We have seen that array elements must be of the same data type. But the Collection members can be of any data type and you don't need to set the size of the Collection object. You can easily add items to the collection and it will grow accordingly.




Creating a Collection

To use a Collection in your code, you first need to declare and create it.

Example:

Dim names As Collection     'Declaring the Collection
Set names = New Collection   'Creating the Collection


Or, replace the above code with this one line code

Dim names As New Collection   'Declaration and creation




Adding items to a Collection : The Add method

You can add one item at a time using the Add method. 


Example: 
Dim names As New Collection

names.Add "john"

names.Add "david"


You may use a string key associated with the item. The string key is used to refer to a Collection item.

Dim names As New Collection

names.Add "John", "one"   ' "one" is the string key, used to refer to the item



Retrieving item values : The Item method

You can refer to a particular item of the collection using the Item method. Here you may use either the index or key value. The index value starts from 1.
Syntax : Collection_Name.Item(Index)
or,          Collection_Name.Item(Key)

Example: Retrieving a particular item using the index of the item

Private Sub cmdShow_Click()
    Dim names As New Collection

    names.Add "John", "one"
    names.Add "David"

    Print names.Item(2) '2 is the index of the item

End Sub

Output: David


Example: Retrieving a particular item using the string key of the item

Private Sub cmdShow_Click()
    Dim names As New Collection

    names.Add "John", "one"
    names.Add "David"

    Print names.Item("one")

End Sub

Output: John


The Item method is the default member of the Collection class, so you may omit it in your code.


Example:

Private Sub cmdShow_Click()
    Dim names As New Collection

    names.Add "John", "one"
    names.Add "David"

    Print names("one")
    Print names(2)

End Sub

Output: 

John
David