Collection.Add Method


Collection.Add Method

Class

Microsoft.VisualBasic.Collection

Syntax

     objectVariable.Add(item[, key[, before[, after]]]) 


objectVariable (required; Collection)

The instance of a Collection to which an item is to be added.


item (required; any)

The new item to add to the collection.


key (optional; String)

A unique string expression that specifies a key that can be used, instead of a positional index, to access a member of the collection.


before (optional; Object)

The existing collection member immediately before which the new member will be inserted. If after is used, this argument must be left blank. Either a numeric position or a key (String).


after (optional; Object)

The existing collection member immediately after which the new member will be inserted. If before is used, this argument must be left blank. Either a numeric position or a key (String).

Description

The Add method adds an object to a collection with an optional search key and, optionally, at a specific ordinal position. The new item may be of any type, and that type need not match the type of items already in the collection (unless using the new Visual Basic 2005 generics feature).

Usage at a Glance

  • If you do not specify a before or after value, the member is appended to the end of the collection (in index order).

  • If you do not specify a key value, you will only be able to access the item by position or by iteration using the For Each...Next statement.

  • The before or after argument can refer to an index or a key. For instance, consider the following code:

         Dim someNames As New Collection(  )     someNames.Add("Donna", "111")     someNames.Add("Steve", "222")     someNames.Add("Bill", "333", "222")     MsgBox(someNames.Item(2)) 

    This code adds "Bill" just before "Steve." The following statement could also be used to achieve the same ordering of items.

         someNames.Add("Bill", "333", 2) 

  • Key values must be unique, or an error occurs.

  • You can use named parameters to add items.

         unitedStates.Add(Key:="MT", Item:="Montana") 

Version Differences

Visual Basic 2005 adds support for generics to several collection-style classes. Generics are discussed in Chapter 10.

See Also

Collection Class, Collection.Count Property, Collection.Item Property, Collection.Remove Method




Visual Basic 2005(c) In a Nutshell
Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))
ISBN: 059610152X
EAN: 2147483647
Year: 2004
Pages: 712

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net