Collection.Add Method (Object, String, Object, Object)
Adds an element to a Collection object.
Assembly: Microsoft.VisualBasic (in Microsoft.VisualBasic.dll)
public void Add( object Item, string Key = null, object Before = null, object After = null )
Required. An object of any type that specifies the element to add to the collection.
Optional. A unique String expression that specifies a key string that can be used instead of a positional index to access this new element in the collection.
Optional. An expression that specifies a relative position in the collection. The element to be added is placed in the collection before the element identified by the Before argument. If Before is a numeric expression, it must be a number from 1 through the value of the collection's Count property. If Before is a String expression, it must correspond to the key string specified when the element being referred to was added to the collection. You cannot specify both Before and After.
Optional. An expression that specifies a relative position in the collection. The element to be added is placed in the collection after the element identified by the After argument. If After is a numeric expression, it must be a number from 1 through the value of the collection's Count property. If After is a String expression, it must correspond to the key string specified when the element referred to was added to the collection. You cannot specify both Before and After.
The Before or After argument must refer to an existing element of the collection; otherwise, an error occurs.
If both the Before and After arguments are omitted, the new object is added to the end of the collection.
An error also occurs if a specified Key value matches the key for an existing element of the collection.
The following 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 Button controls 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 event handlers for the Add and List buttons as shown. The Add button allows you to add children. The List button displays 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 ' Create a Collection object. Private family As New Collection() Private Sub addChild_Click() 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 listChild_Click() Handles Button2.Click For Each aChild As child In family MsgBox(aChild.name) Next End Sub
Available since 1.1
Available since 2.0