|
|
Title | Build a strongly typed collection class |
Keywords | custom collection, strongly typed collection, For Each, ForEach |
Categories | Classes |
|
|
See the HowTo Build a custom collection class that supports For Each for instructions on building a custom collection class that supports a default method and For Each. That collection behaves more or less like a normal collection.
You can enhance this collection to provide additional features. To make the collection strongly typed, modify the Add method so its Item parameter has a specific data type. You can also add data validation. The following code allows the program to add only OrderItem objects to the collection. It also verifies that each OrderItem has a non-blank Name value and a Quantity of at least 1.
When it adds a new item, it raises the ItemAdded event so the main program can take action if necessary. You could add siilar events to other methods. For example, you could raise a BeforeRemove event in the Remove subroutine. If you pass a Cancel parameter to the event ByRef, the main program could set Cancel to True to tell the Remove subroutine to cancel the removal.
|
|
Public Event ItemAdded()
' Add an item to the collection.
Public Sub Add(ByVal Item As OrderItem, Optional ByVal key _
As Variant, Optional ByVal before As Variant, Optional _
ByVal after As Variant)
' Make sure the new item contains valid data.
If Len(Item.Name) = 0 Then
Err.Raise 1, "OrderItemCollection.Add", _
"OrderItem must have a non-blank Name."
End If
If Item.Quantity < 1 Then
Err.Raise 1, "OrderItemCollection.Add", _
"OrderItem must have Quantity > 0."
End If
' Add the item.
m_Items.Add Item, key, before, after
' Raise the ItemAdded event.
RaiseEvent ItemAdded
End Sub
|
|
|
|
|
|