[AccessD] Advanced Unbound Form With Classes and Collections Part 3

DWUTKA at marlow.com DWUTKA at marlow.com
Tue Jun 27 13:58:08 CDT 2006


We have built a 'collection class' in our demo, the People Class.  It is an
object representing all of the people in our database.  We can retrieve
people from it either with their ID, or by their sort order (first or last
name sort).

 

But why can't we do a For Next loop?  I mean, our class represents multiple
Persons, so it contains all of the Person classes, why are we forced to use
an index or position to retrieve a person?

 

Surprise, we're not.  Though to get this capability requires a little
'outside of the box' work.  Here's what we need to do.  First, we need to
add a function to our People class:

 

Public Function NewEnum() As IUnknown

Set NewEnum=PeopleByFirst.[_NewEnum]

End Function

 

The next portion is a little tricky in Access.  We need to set this
procedure's 'id' to -4.  In Visual Basic 6, you can do this by clicking
Tools>Procedure Attributes, and then clicking the Advanced button.  I
looked, couldn't find this in Access, but all's not lost.  We can still do
this.  Right click on the People class in our demo project's code window.
Select Export File.  Save it somewhere.  Now go and open that saved file in
Notepad.  You'll see the code of our class with some extra stuff thrown in.
What we need to do is add a line in our NewEnum function so it looks like
this:

 

Public Function NewEnum() As IUnknown

Attribute NewEnum.VB_UserMemId = -4

Set NewEnum=PeopleByFirst.[_NewEnum]

End Function

 

Once this is done, let's test it.

 

Create a form with a button, and put the following code behind it:

 

Dim ps as Person

Dim ppl as People

Set ppl=New People

For Each ps in ppl

            Debug.print ps.FullName

Next

Set ps=nothing

Set ppl=nothing

 

Now press the button and run our test code.  Whalla!  We can now loop
through the Person objects in our People Collection with a For Next loop!

 

So now that we know about collections, and we have created the same
functionality of a collection with our own 'collection class', let's go a
step further, and make our Person class 'aware' of it's collection class.
We'll do this in the next part.

 

Drew




More information about the AccessD mailing list