Share via


Contains Method (Collection Object) 

Returns a Boolean value indicating whether a Visual Basic Collection object contains an element with a specific key.

Public Function Contains( _
    ByVal Key As String _
) As Boolean

Parameters

  • Key
    Required. A String expression that specifies the key for which to search the elements of the collection.

Exceptions/Error Codes

Exception type Error number Condition

ArgumentException

5

The specified Key is Nothing.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You can compare the error number against the Number Property (Err Object).) However, when possible, you should consider replacing such error control with Structured Exception Handling Overview for Visual Basic.

Remarks

Contains returns True if the collection contains an element with a key exactly matching Key. Otherwise, Contains returns False.

A Visual Basic Collection can hold some elements that have keys and other elements without keys. This depends on whether the call to the Add Method (Collection Object) supplies an argument to the optional Key parameter.

Example

Dim customers As New Microsoft.VisualBasic.Collection()
Dim accountNumber As String = "1234"
' Insert code that obtains new customer objects.
' Use the new customer's account number as the key.
customers.Add(newCustomer, accountNumber)
' The preceding statements can be repeated for several customers.
Dim searchNumber As String = "1234"
' Insert code to obtain an account number to search for.
If customers.Contains(searchNumber) Then
    MsgBox("The desired customer is in the collection.")
Else
    MsgBox("The desired customer is not in the collection.")
End If

If you intend to search the collection for elements using their keys, remember to supply the Key argument every time you call the Add method.

Requirements

Namespace: Microsoft.VisualBasic

Module: Collection

Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)

See Also

Reference

Collection Object (Visual Basic)
Item Property (Collection Object)
Count Property (Collection Object)
Add Method (Collection Object)
Remove Method (Collection Object)
Clear Method (Collection Object)