Visual Basic 6 Database How-To

Previous chapterContents


- E -
A Short Introduction to Visual Basic Objects



The introduction of Visual Basic 5 made object-oriented programming much easier. This appendix defines and discusses objects as well as illustrates how to use them.

Object Overview

The biggest selling point of object-oriented programming is encapsulation. Encapsulation means that both the data and the means of transforming or altering that data is wrapped up into one easy-to-use shell called an object. In its simplest form, an object is a group of data describing a particular item that cannot be described by a single number or string.

For instance, imagine that you want to make yourself the object in which to store your application. With a single variable, you can give yourself a name. Most likely you need much more information than this to describe yourself. You might want to indicate your age and possibly your address. It is possible to incorporate all this information into one structure that represents you. Take, for example, the following type declaration:

Private Type Person
    Name As String
    Age As Integer
    Address As String
    City As String
    State As String
    ZipCode As String
End Type

This declaration creates a new data type called Person that can hold a person's name, age, address, city, state, and zip code. To create a new person, you would use something similar to the following declaration:

Private Steven As Person

This data structure was acceptable to Visual Basic programmers until version 6, when developers suddenly demanded more (and we have the right!).

Now, in Visual Basic 6, you can include much more in a data structure than just the data. Using encapsulation, you can add methods and events. The data, as we know it, becomes properties. Properties are user-interface variables or variable objects. With these interfaces, you can cleanly access the data for what is now called a class.

The concept of classes was not developed for Visual Basic; it was developed a long time ago for much older languages. (If I quote a language that invented classes or object-oriented programming, I know I will receive hate mail telling me of an earlier programming language, so I'll be vague in my history.) What's important is that you have the ability to use classes now in Visual Basic.

A class is similar to a type declaration in that it is a framework or a shell used to hold and manipulate data; however, no data or manipulation occurs in the class itself. To work with this structure, you must create an instance of the class by declaring a variable--an object variable:

Private m_oNewPerson As New Person

Here, Person is no longer the name of a data structure but rather the name of a class that would hold properties called Name, Age, Address, and so on. You would also have methods within this class to manipulate this information. For instance, you might have a method that is part of the Person class that would load a person's information from a file. In this case, you might have a Load method, as in this example:

m_oNewPerson.Load "Steven"

This example accepts a string as an argument to determine the name of the person to load.

There have always been objects in Visual Basic, even if you haven't realized it. Take, for instance, the TextBox control. This is an object--an instance of the text box class. You can use object-oriented programming to access the properties of a TextBox control as shown in this procedure:

Private Sub DoSomethingSenseless()
    Text1.Enabled = True
    Text1.Text = "Hello Mommy!"
    Text1.SelStart = 0
    Text1.SelLength = Len(Text1.Text)
End Sub

This example simply sets various properties of the TextBox control to what you have specified. You also read one of the properties from the TextBox control (Text1.Text), as shown in the last line.

You can call methods of this control in a fashion similar to this:

Text1.SetFocus

In this example, you simply called the SetFocus method that puts the focus of the window to the TextBox control.

The DoSomethingSenseless routine shown previously takes advantage of a great interface to the TextBox control. However, there is an even more object-oriented approach you can choose to take, as shown in this newly revised DoSomethingSenseless routine:

Private Sub DoSomethingSenseless()
    With Text1
        .Enabled = True
        .Text = "Hello Mommy!"
        .SelStart = 0
        .SelLength = Len(.Text)
        .SetFocus
    End With
End Sub

This routine uses a statement called With. With uses the Text1 control to access its public members.

Many objects have default properties. The TextBox control's default property is the Text property. The following example shows how you can access the default property:

Private Sub DoMoreThings()
    ` declare a new object and call it oNewObject
    Dim oNewObject As Object
    ` all objects can be set to the `root' type of Object
    Set oNewObject = Text1
    ` the following are equivalent
    oNewObject.Text = "Hello Dad!"
    oNewObject = "Hello Dad!"
    Text1.Text = "Hello Dad!"
    Text1 = "Hello Dad!"
End Sub

Notice the declaration of a new object variable in the beginning of this routine. All objects can be assigned to the Object data type. This means that all objects implement the object class. After you have the new object, you can set it to the Text1 control (actually, just give it a reference to the control). This step allows you to access your Text1 control using the oNewObject object variable. Also notice that the Text property does not have to be entered to assign the property its value because it is the object's default value.

Your Own Object

You can create your own object definition, or class, using Visual Basic 6. To do so, first create a new project. Along with Form1, which should already be part of your new project, add a class module. Name the class Person, and add the following code to the declarations section of the class module:

Option Explicit
Private m_sFirstName As String
Private m_sLastName As String

These two member variables of the Person class are private variables--they cannot be accessed by anybody outside of your class.

Now add your public properties, which serve as your user interface to retrieve information from the user:

Public Property Let FirstName(ByVal sNewValue As String)
    m_sFirstName = sNewValue
End Property
Public Property Let LastName(ByVal sNewValue As String)
    m_sLastName = sNewValue
End Property

Please note that there are no Property Get routines for the FirstName and LastName properties. This means that the properties are write-only and cannot be read.

Now create a property that allows the user to retrieve the entire name of the Person class as shown here:

Public Property Get FullName() As String
    FullName = m_sFirstName & " " & m_sLastName
End Property

This is a Property Get routine, and there is no Property Let routine, so this property is read-only.

You can now use your new class in a routine to create a new Person object:

Private Sub CreatePerson()
    Dim oNewPerson As New Person
    With oNewPerson
        ` retrieve information from the user
        .FirstName = InputBox$("Enter first name:")
        .LastName = InputBox$("Enter last name:")
        ` display the full name for the user
MSGBOX "PERSON'S FULL NAME: " & .FULLNAME
    End With
End Sub

This routine declares a new instance of the Person class that you wrote earlier. The user is then asked for the first and last name of the new person, and both strings are stored in the corresponding property. Finally, the FullName property is called to show the user the full name of the new person.

Collections of Objects

Collections are used to group related data objects into a single set. In DAO, collections are everywhere--from the Workspaces collection to the Fields and Indexes collections.

A collection is a good place to keep a list of objects. For instance, take the Person class shown previously. Suppose you want to add many people to a group or list. In this case, it would be good to use the Collection class to keep track of the people. Take the following event, for example:

Public Persons As New Collection
Private Sub cmdAddPerson_Click()
    ` initiate a new person object
    Dim oNewPerson As New Person
    With oNewPerson
        ` get new name from the user
        .FirstName = InputBox$("Enter first name:")
        .LastName = InputBox$("Enter last name:")
        ` add the person to the persons collection
        Persons.Add .FullName
    End With
End Sub

This event fires when a person presses a command button. First, a new Person object is initiated from the Person class. Next, the person's first and last names are filled. Finally, the person is added to the collection using the Add method of the Persons collection.

The Collection class stores all items as Variant data types. Therefore, you can add any data type to a collection object, with the exception of user-defined types. This also means that you can add different types to the same collection because the Collection class cannot tell the difference anyway.

Table E.1 shows the property and three methods of the Collection class.

Table E.1. The Collection class.

METHOD OR PROPERTY Description
Count property Returns the number of items belonging to the current collection object
Add method Adds a new item to the current collection object
Item method Returns an item, by an index or a key, from the current collection object
Remove method Removes an item from the current collection, by an index or a key

As you can see, the Collection class is pretty straightforward. Although arrays are more efficient memory managers than collection objects, they cannot compete with other advantages. For one, you never need to use ReDim with a collection object--it takes care of its size for you. Also, the Collection class can access its items very quickly using the Item method, whereas an array does not have this built-in functionality.

An item of a collection is retrieved, removed, or added to a collection object, using a key and an index. A key is a string used during the Add method call, whereas an index is usually determined after each object is added to a collection. An index is a long value that can be determined by using the before and after parameters; however, the index can change after another object is added to the collection.

You can use the index to iterate through a collection to access each item, as shown in this example:

Dim nCount As Integer
With Persons
    For nCount = 1 To .Count
        Debug.Print .Item(nCount).FullName
    Next nCount
End With

This code uses the Count property of the Persons collection to determine an upper bound for the For...Next loop. For each item in the collection object Persons, the FullName property is printed to the Immediate Window.

An easier and more efficient way to iterate through a collection is to use the For Each...Next statement instead of the For...Next, as shown in this code:

Dim oPerson As Person
For Each oPerson In Persons
    Debug.Print oPerson.FullName
Next nCount

This code declares a new object variable called oPerson as a Person object. Using this variable, the For Each oPerson In Persons line of code sets oPerson to each Persons.Item(index) object in the collection. Now you can use the oPerson object to access the collection object.

Adding an Item to a Collection Object

To add items to a collection, you would use the Add method with the following syntax:

Sub Add (item As Variant [, key As Variant] [, before As Variant]
                                            [, after As Variant])

The first parameter to the routine is the actual object you are to add to the collection, and the second is a key that would be used to quickly search for the given object. The following statements demonstrate the use of keys in a collection:

Persons.Add oNewPerson, oNewPerson.FullName
Persons.Add oNewPerson, "Jason"

The other two parameters for the Add method are the before and after parameters. By using one of these two parameters, you can specify the ordinal position of your item in the collection object as shown in these examples:

Persons.Add oNewPerson, "Jason", 1             ` adds as first item
Persons.Add oNewPerson, "John", before:=3      ` adds as second item
Persons.Add oNewPerson, "Kimberly", after:=6   ` adds as seventh item

As you can see, the Add method supports named arguments.

Removing an Item from a Collection Object

To delete an item from a collection, you must know the index or the key of the item intended for deletion. The syntax for the Remove method is as follows:

Sub Remove (index As Variant)

The index argument in the Remove method can be either the item's key or the item's index number.

Following are a couple examples of the Remove method:

Persons.Remove 5
Persons.Remove "Jason"

Accessing Items in a Collection Object

To access items in a collection, you can use the Item method. The syntax for the Item method is as follows:

Function Item (index As Variant) As Variant

You must use the Set statement when the Item being returned is an object variable. The index argument is either the key or the index of the item in the collection object, as shown in these examples:

SET ONEWPERSON = PERSONS.ITEM(6)

Set oNewPerson = Persons.Item("Jason")
Set oNewPerson = Persons(6)
Set oNewPerson = Persons("Jason")

Notice the last two statements. The Item method is omitted because it is the default method for the Collection class.


Previous chapterContents

© Copyright, Macmillan Computer Publishing. All rights reserved.