Collection.Add Method

   
Collection.Add Method

Class

Microsoft.VisualBasic.Collection

Syntax

   objectvariable.Add item   [,   key, before, after   ] 
objectvariable (required; Collection Object)

The name of the Collection object to which an item is to be added

item (required; Object)

An object of any type that specifies the member to add to the collection

key (optional; String)

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

before (optional; Object)

The member to be added placed in the collection before the member identified by the before argument (more on this in Section )

after (optional; Object)

The member to be added placed in the collection after the member identified by the after argument (more on this in Section )

Description

Adds an object to a collection

Rules 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 cannot access this member using a key , but instead must access it either by using its ordinal number or by enumerating all the members of the collection with the For Each...Next construct. Thus, keys are highly recommended.

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

     Dim c As New Collection(  ) c.Add("donna", "111") c.Add("steve", "222") 'c.Add("bill", "333", "222") 'c.Add("bill", "333", 2) MsgBox(c.Item(2)) 

    Both of the commented lines of code adds the item "bill" between "donna" and "steve." The first line uses the key to specify the before object, and the second line specifies the ordinal position of the before object.

  • Key values must be unique or an error (runtime error 457, "This key is already associated with an element of this collection") is generated.

  • You can specify a before or after position, but not both.

Example

 colComposers.Add(Item:="Ludwig von Beethoven" _                   Key:="Beethoven") 

Programming Tips and Gotchas

  • Using named parameters helps to self-document your code:

     colMyCollection.Add Item:="VB.NET Language in a Nutshell" _                     Key:="Title" 
  • If your key parameter is a value being brought in from outside your program, you must ensure that each value is always unique. One method for doing this is illustrated in the entry for the Collection.Item Method.

See Also

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

   


VB.Net Language in a Nutshell
VB.NET Language in a Nutshell
ISBN: B00006L54Q
EAN: N/A
Year: 2002
Pages: 503

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