Adds a member to a Collection object.
Public Sub Add( _
ByVal Item As Object, _
Optional ByVal Key As String, _
Optional ByVal { Before | After } As Object = Nothing _
)
| Exception type | Error number | Condition |
|---|---|---|
| 5 | Both Before and After are specified, or argument does not refer to an existing member of the collection. | |
| 5 | The specified Key already exists. |
The Before or After argument must refer to an existing member of the collection; otherwise, an error occurs.
An error also occurs if a specified Key value matches the key for an existing member of the collection.
This example uses the Add method to add Child objects instances of a class called Child containing a Public property Name to a collection called Family. To see how this works, create a Form with two Buttons and set their Text properties to Add and List. Add the Child class definition and the Family declaration to the form code. Modify the Click events for the Add and List buttons as shown. The Add button allows you to add children. The List button will display the names of all the children.
Public Class Child
Public Name As String
Sub New(ByVal newName As String)
Name = newName
End Sub
End Class
Private family As New Collection() ' Create a Collection object.
Private Sub Add_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim newName As String
newName = InputBox("Name of new family member: ")
If newName <> "" Then
family.Add(New Child(newName), newName)
End If
End Sub
Private Sub List_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
Dim aChild As Child
For Each aChild In family
MsgBox(aChild.Name)
Next
End Sub
Item Property | Remove Method |