programming with collection

H

Hills

Hi, I really can't know it myself how to know a key that has already been
added in a collection, and vise versa, that a key is not in the collection.

Here is my code in a form
'=========================================================
Public orderCollection As New Collection
'=========================================================
Private Sub test(orderID As Integer)
Dim order As New Form_Order
'here I want to add code to see if Cstr(orderID) is already
'a key in the collection. But I don't know how to do it.
orderCollection.Add order, Cstr(orderID)
order.visible = true
End Sub

I want to use orderCollection to keep each instance of the order form with
it's orderID as a key. So a multiple instance of order form can be opened.
When it is closed, it's quite simple to use collection.remove method to
remove a key, and add a key is simple too.

But I don't know how to make sure that a key has already been added to the
collection or a key is not added.

So far the only way I found is to add the key anyway, and catch the "key
already in collection" error and set the order to nothing if adding a
duplicated key.

Any better ideas?

TIA.
 
D

Dan Artuso

Hi,
Try this function:

Public Function KeyExists(col As Collection, key As String) As Boolean
Dim ret As Variant
On Error Resume Next
ret = col.Item(key)
If err.Number <> 0 Then
KeyExists = False
Else
KeyExists = True
End If
End Function

You can call it like:
If KeyExists(orderCollection,Cstr(orderID)) Then
'its there
Else
'its not
End If
 
H

Hills

Thanks a lot Dan. It's looks much better and more professional than what I
was coding. I will use it. Thanks again.

My original code is something like:

Private Sub Test(orderID As Integer)
On error goto catch
Dim f As New form_orderForm
orderFormCollection.Add f, Cstr(orderID)
f.visible = true
finally:
exit sub
catch:
'/// if err.number = the runtime error number that adding duplicated key
then
'/// bring up that instance in front of all other instances
'/// resume finally
'/// end if
End Sub

Now the code will be:

Private Sub Test(orderID As Integer)
Dim f As orderForm
If KeyExists(orderCollection,Cstr(orderID)) Then
'///simply bring up that instance above all other windows
else
set f = new form_orderForm
orderFormCollection.Add f, Cstr(orderID)
f.visible = true
end if
End Sub

It looks much better now.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top