Collection [Part 2] - Visual Basic 6



Using the Before and After argument of the Add method

You can choose to store the item values exactly where you want using the Before and After argument of the Add method.

Example:

Private Sub cmdShow_Click()

     Dim items As New Collection

     items.Add "one"
     items.Add "two"
     items.Add "three", , 1

     For i = 1 To 3

        Print items.Item(i)
     Next i
End Sub

Output:

three
one
two




Removing an item : The Remove method

You can remove a particular item from the Collection using the Remove method.

Example:

Private Sub Command1_Click()
     Dim country As New Collection
     country.Add "USA"
     country.Add "UK"
     country.Add "Japan", "j"

     country.Remove (1)
     country.Remove ("j")

End Sub




Number of items in a Collection : The Count method

Example:
Private Sub cmdCount_Click()
     Dim country As New Collection
     country.Add "USA"
     country.Add "India"
     country.Add "Japan", "j"

     Dim n As Integer
     n = country.Count
     Print n

End Sub

Output: 3




Retrieving the last item 

Example:
Private Sub Command1_Click()
     Dim country As New Collection
     country.Add "Germany"
     country.Add "India"
     country.Add "China", "j"

     Print country.Item(country.Count)
End Sub

Output: China





Deleting all items from the Collection

Use a Do While loop to delete all item from the Collection object.

Example: 

Private Sub cmdDeleteAll_Click()
     Dim country As New Collection
     country.Add "Bangladesh"
     country.Add "Australia"
     country.Add "Russia", "j"

     Do While (country.Count > 0)
        country.Remove 1
     Loop

     Print country.Count
End Sub

Output: 0


Another way to delete all items is to destroy the Collection object. The following code destroys the Collection object and thus deletes all the items.

Set items = Nothing
'Or,
Set items = New Collection