Chapter 4: Creating Your Own Objects


Now that you understand basic object-oriented programming concepts, you can turn your attention to the topic of creating your own objects. This chapter will provide a brief summary of what you have learned so far and will then teach you why and how to create custom class modules with associated properties, methods, and events. It will also cover how to extend existing objects, such as forms or controls, by adding custom properties, methods, and events. As with most other chapters, you can download the database containing the code for this chapter from Wrox.com.

Using Class Modules to Create Your Own Objects

As you have already learned, an object refers to all the things that make up your database, including forms, reports, and controls. By encapsulating code into objects, you make programs easier to maintain and code easier to reuse. You also have learned that objects can have properties, methods, and events. Properties are characteristics of the object, and methods are actions you take upon the object. Events are triggered when a user or application performs an action. These objects, which you worked with in Chapter 3, were created using class modules, although you did not see the proprietary source code for the Access objects.

You may remember from Chapter 2 that a class module is only one of the two types of modules; the other type is a standard module. Standard modules are modules that contain procedures that are not associated with any particular object. The procedures you wrote in the modBusinessLogic module in Chapter 2 were placed in a standard module. Class modules are modules that are associated with a particular object. Class modules can be used either for form or report modules or for custom objects. For example, form and report class modules can contain code that corresponds to a particular form or report, such as the event procedures for forms and controls that you wrote in the corresponding form class module in an earlier chapter. Since Access 97, class modules can also be created independently of a form or report and, in such cases, are used to create a definition for a custom object. This chapter will focus on using class modules for creating custom objects, as well as extending the class modules of existing objects with custom properties, methods, and events.

Go ahead and create a new database to use with the examples in this chapter. Select the Office Button image from book New image from book Blank Database and specify Ch4CodeExamples as the file name.

You can insert a new class module in three ways. One way is to select the Create ribbon from the toolbar, and then select Class Module in the area of the toolbar labeled Macro. The drop-down with the Create Module option displays Macro, Module, and Class Module as the options in the list. Another way to insert a new class module is from the Visual Basic Editor by selecting Insert image from book Class Module. A final way is to right-click on the Project Explorer from within the Visual Basic Editor and select Insert image from book Class Module from the pop-up menu.

Now that you have the empty database created, let’s temporarily divert your attention to learn how custom objects should be documented using Class Diagrams during the design phase. I’ll then give you the details on how to create custom objects.

Class Diagrams

Before jumping into the techniques for coding custom objects, you must understand how custom objects fit into the Systems Development Life Cycle and how to identify and document what custom objects you should create. You learned in Chapter 1 that during the design phase of your application you generate a written specification for how your application should be coded. Activity Diagrams, Use Case Diagrams, and screen prototypes are examples of some techniques that can be used to document your design. Class Diagrams are another documentation technique.

You are already well aware that an object can have properties, methods, and events. Your application should certainly make use of existing Access objects where possible, so that you do not have to rewrite code that the Microsoft programmers have already written for you. However, as appropriate, you should also take advantage of custom objects to maximize the unique features of your application. During the design phase, you should identify the custom objects for your application and document the custom objects using Class Diagrams.

Class Diagrams are critical in object-oriented system designs. They show the classes, relationships within the classes, and the way the code should be structured. In a Class Diagram, the properties and methods that make up an object are portrayed graphically. For example, in the case of the hypothetical Wrox Auto Sales Application described in Chapter 1, you deal with cars. Figure 4-1 shows the sample prototype screen for managing cars, as discussed in Chapter 1.

image from book
Figure 4-1

An object that you might want to create is a Car object. You could use a Car class to represent the Car object. The user interface is often a good starting point for determining properties and methods of an object. The Car object can have certain properties: Make, Model, Year, and so on, as the fields on the user interface indicate. In addition to these properties, the Car object needs methods that allow for retrieving, adding, updating, and deleting a specific record. These methods correlate to the Lookup, Add New, Save, and Delete buttons on the user interface.

Figure 4-2 shows an example Class Diagram for the Car object.

Car

  • -VehicleIdNumber

  • - MakeId

  • - ModelId

  • - Year

  • - Mileage

  • - ColorId

  • -InteriorTypeId

  • -InteriorColorId

  • -TransmissionTypeId

  • - StatusId

  • - ReceivedDate

  • - SoldDate

  • - SoldToCustomerId

  • - Photo

  • - Special Features

  • +Retrieve ()

  • +Add()

  • +Update()

  • +Delete()


Figure 4-2

Notice that the properties for the Car class are listed first, followed by a divider line and then by the methods it contains. The Class Diagram in Figure 4-2 contains the tracked properties and the methods for which you must write code. When you create a new system, create a Class Diagram that depicts all objects in the entire system. This is not an easy task and requires effort and time to learn. For the sake of simplicity, I focus on writing custom properties, methods, and events for the Car class of the hypothetical Wrox Auto Sales.

Tip 

A complete solution would contain other class modules as well, such as one for a Customer object or a SearchInventory object. The comprehensive case studies in Chapters 13 and 14 will include complete Class Diagrams for the respective systems and are excellent resources for refining your understanding of documenting and creating custom objects.

In Chapter 1, I mentioned that your code can be separated into three different logical tiers, even though Access is not used for physical three-tier applications. In most cases, it is a good idea to separate your code into different logical tiers. This makes it easier to update a particular portion of the application and migrate it to other platforms.

Returning to the Car class example, I will walk you through adding additional Class Diagrams based on the separation of tiers concept. You can actually create the Class Diagrams in any order you choose, but my personal preference is to start with the business logic layer first. The business logic layer is where you put your main classes like Car, and everything else revolves around it.

The Class Diagram in Figure 4-2 fits into the business logic layer. Now that you have created the business logic layer of the application, the other two remaining layers are really easy to create. Any call to the database will be included in a class in the data access layer. For each business logic layer class module that has a method requiring data from the database, you create a corresponding class module in the data access layer. Thus, the business logic layer (the Car class) will not make any calls directly to the database to get data. Instead, the Car class calls a method in a CarDb class in the data access layer, which, in turn, gets the data from the database, as you can see in Figure 4-3.

image from book
Figure 4-3

After creating the business logic layer and data access layer Class Diagrams, you create the diagrams for the presentation (user interface) layer. This is probably the easiest of the three to create, because you simply put each of your use cases on the diagram. Remember the use cases you created in Chapter 1 that defined each of the independent actions the user can take in the Wrox Auto Sales Application from the user interface? As Figure 4-3 illustrates, you can just list the use cases for the presentation layer class modules because the use cases define the user interface services to be performed.

Notice how each of the layers is connected appropriately to the others in the instances where they communicate with each other. For example, the Open Car action on the presentation layer calls the Retrieve method on the Car class, which in turn calls the RetrieveCarDb method on the CarDb class. The code to implement the presentation layer usually goes in class modules associated with the related form or report. The code to implement the business logic layer and data access layer ideally goes in custom class modules, although other variations are also possible and acceptable. I hope you are starting to see how this isolation of application logic into tiers works.

At this point, don’t worry about understanding the complex details of designing class modules for an entire application. You should just understand that Class Diagrams can be used to model the custom objects that you want to create. I now return to the discussion of creating custom objects, and show you how to write the code to implement the properties and methods listed on the Car object in Figures 4-2 and 4-3.

Creating Properties

To recap, properties are characteristics of an object. Properties for custom classes can be implemented using public variables or using Property Let, Property Get, and Property Set procedures, which are discussed next.

Using Public Variables

One way to create properties for a class is to use a public variable declaration in a class module. In Chapter 2, you learned how to write a public variable declaration. When you place a public variable declaration in the Declarations section of a class module, it becomes a property for that class. Here is an example:

  Public VehicleIdNumber As Double 

I do not recommend creating properties using public variables for several reasons. First, you cannot manipulate the value because the property is set. Second, you cannot create read-only and write-only properties. Third, you cannot easily validate what is assigned to public variables. The better way to create properties is discussed next and does not have these drawbacks.

Using Property Let, Property Get, and Property Set

Property Let, Property Get, and Property Set procedures enable you to create properties in a more flexible way than by using public variables. Property Let procedures determine what happens when you assign a value to the property. Here is a simple example showing the general syntax for a Property Let procedure:

  Public Property Let TestProperty(ByVal strMessage As String)   'code for assigning the property goes here   strTestPropertyVal = strMessage End Property 

In many cases, you assign the value of the parameter passed to the property procedure to a variable that is declared in the Declarations section of the class. The Property Let procedure is a special type of procedure that is executed whenever you assign the property to another value in your code. For example, suppose that you have the following line of code:

  TestProperty = "This is a new value for the property." 

Because you are assigning the TestProperty property to a new value, the Property Let procedure will execute. In the current example, the string value listed in quotation marks is passed to the Property Let procedure as the strMessage parameter and is assigned to a strTestPropertyVal variable.

You can include much more than just a single assignment statement in a Property Let procedure. For example, you can perform validation checks or call other methods from within the Property Let procedure. The following example illustrates performing validation checks before assigning the property value.

  Public Property Let TestProperty(ByVal strMessage As String)     'if the length of the message is less than 25 then set the value     If Len(strMessage) < 25 Then         'code for assigning the property goes here         strTestPropertyVal = strMessage     Else         Msgbox "The message for Test Property cannot exceed 25 characters!"     End If End Property 

You can see in this example how using the Property Let procedure gives you greater flexibility than if you had declared the property as a public variable.

The Property Get procedure is used to specify what should happen upon retrieval of the property’s value. Here is an example of the syntax used for a Property Get procedure:

  Public Property Get TestProperty As String     TestProperty = strTestPropertyVal End Property 

Notice how the name of the property is assigned to the local variable strTestPropertyVal that is being used to store the current value of the property. This is, in effect, a function that returns the value in the local variable upon request. Just like the Property Set procedure, the Property Get procedure can include additional code.

The Property Set procedure is used only to specify what should happen when the value of an object data type is assigned. In all other cases, you should use the Property Let procedure to specify what happens when properties are assigned values.

Tip 

You can create read-only properties by eliminating the Property Let procedure and including only the Property Get procedure.

It’s time to try your hand at creating all the properties for the Car class of the Wrox Auto Sales Application that was analyzed earlier. You may want to refer to Figure 4-2 to see how the Class Diagram maps to the code you write.

Try It Out-Creating the Properties for the Car Class

image from book
  1. If you have not already done so, create a new database for use with the examples in this chapter. To do so, select File image from book New image from book Blank Database. Specify the file name as Ch4CodeExamples and click the Create button.

  2. Add a new class to the database. Open the Database Window and select the Create ribbon from the toolbar, then select Class Module in the area of the toolbar labeled Other. The drop-down with the Create Module option displays Macro, Module, and Class Module as the options in the list. In the Properties Window in the Visual Basic Editor, change the name of the class to clsCar.

  3. Add the following declarations to the General Declarations section of the clsCar class:

      Dim dblVehicleIdNumberVal As Double Dim intMakeIdVal As Integer Dim intModelIdVal As Integer Dim intModelYearVal As Integer Dim intMileageVal As Integer Dim intColorIdVal As Integer Dim intInteriorTypeIdVal As Integer Dim intInteriorColorIdVal As Integer Dim intTransmissionTypeIdVal As Integer Dim intStatusIdVal As Integer Dim dtReceivedDateVal As Date Dim dtSoldDateVal As Date Dim intSoldToPersonIdVal As Integer Dim strPhotoVal As String Dim strSpecialFeaturesVal As String 

  1. Add the property procedures for VehicleIdNumber to the clsCar class:

      Public Property Get VehicleIdNumber() As Double     VehicleIdNumber = dblVehicleIdNumberVal End Property Public Property Let VehicleIdNumber(ByVal Value As Double)     dblVehicleIdNumberVal = Value End Property 

  2. Add the property procedures for MakeId to the clsCar class:

      Public Property Get MakeId() As Integer     MakeId = intMakeIdVal End Property Public Property Let MakeId(ByVal Value As Integer)     intMakeIdVal = Value End Property 

  3. Add the property procedures for ModelId to the clsCar class:

      Public Property Get ModelId() As Integer         ModelId = intModelIdVal End Property Public Property Let ModelId(ByVal Value As Integer)     intModelIdVal = Value End Property 

  4. Add the property procedures for ModelYear to the clsCar class:

      Public Property Get ModelYear() As Integer        ModelYear = intModelYearVal End Property Public Property Let ModelYear(ByVal Value As Integer)     intModelYearVal = Value End Property 

  5. Add the property procedures for Mileage to the clsCar class:

      Public Property Get Mileage() As Integer     Mileage = intMileageVal End Property Public Property Let Mileage(ByVal Value As Integer)     intMileageVal = Value End Property 

  1. Add the property procedures for ColorId to the clsCar class:

      Public Property Get ColorId() As Integer     ColorId = intColorIdVal End Property Public Property Let ColorId(ByVal Value As Integer)     intColorIdVal = Value End Property 

  2. Add the property procedures for InteriorTypeId to the clsCar class:

      Public Property Get InteriorTypeId() As Integer     InteriorTypeId = intInteriorTypeIdVal End Property Public Property Let InteriorTypeId(ByVal Value As Integer)     intInteriorTypeIdVal = Value End Property 

  3. Add the property procedures for InteriorColorId to the clsCar class:

      Public Property Get InteriorColorId() As Integer     InteriorColorId = intInteriorColorIdVal End Property Public Property Let InteriorColorId(ByVal Value As Integer)     intInteriorColorIdVal = Value End Property 

  4. Add the property procedures for TransmissionTypeId to the clsCar class:

      Public Property Get TransmissionTypeId() As Integer     TransmissionTypeId = intTransmissionTypeIdVal End Property Public Property Let TransmissionTypeId(ByVal Value As Integer)     intTransmissionTypeIdVal = Value End Property 

  5. Add the property procedures for StatusId to the clsCar class:

      Public Property Get StatusId() As Integer     StatusId = intStatusIdVal End Property Public Property Let StatusId(ByVal Value As Integer)     intStatusIdVal = Value End Property 

  1. Add the property procedures for ReceivedDate to the clsCar class:

      Public Property Get ReceivedDate() As Date     ReceivedDate = dtReceivedDateVal End Property Public Property Let ReceivedDate(ByVal Value As Date)     dtReceivedDateVal = Value End Property 

  2. Add the property procedures for SoldDate to the clsCar class:

      Public Property Get SoldDate() As Date     SoldDate = dtSoldDateVal End Property Public Property Let SoldDate(ByVal Value As Date)     dtSoldDateVal = Value End Property 

  3. Add the property procedures for SoldToPersonId to the clsCar class:

      Public Property Get SoldToPersonId() As Integer     SoldToPersonId = intSoldToPersonIdVal End Property Public Property Let SoldToPersonId(ByVal Value As Integer)     intSoldToPersonIdVal = Value End Property 

  4. Add the property procedures for Photo to the clsCar class:

      Public Property Get Photo() As String     Photo = strPhotoVal End Property Public Property Let Photo(ByVal Value As String)     strPhotoVal = Value End Property 

  5. Add the property procedures for SpecialFeatures to the clsCar class:

      Public Property Get SpecialFeatures() As String     SpecialFeatures = strSpecialFeaturesVal End Property Public Property Let SpecialFeatures(ByVal Value As String)     strSpecialFeaturesVal = Value End Property 

  6. Click the Save button on the toolbar to save your changes to the class.

How It Works

First, you created a new class module in the database and named it clsCar. You then added the local variables that are used later by the Property Get and Property Set procedures for each property, as shown in the following code.

 Dim dblVehicleIdNumberVal As Double Dim intMakeIdVal As Integer Dim intModelIdVal As Integer Dim intModelYearVal As Integer Dim intMileageVal As Integer Dim intColorIdVal As Integer Dim intInteriorTypeIdVal As Integer Dim intInteriorColorIdVal As Integer Dim intTransmissionTypeIdVal As Integer Dim intStatusIdVal As Integer Dim dtReceivedDateVal As Date Dim dtSoldDateVal As Date Dim intSoldToPersonIdVal As Integer Dim strPhotoVal As String Dim strSpecialFeaturesVal As String

Next, you added Property Get and Property Let procedures for each property in the class. For example, you added Property Get and Property Let procedures to the VehicleIdNumber property to specify what happens whenever the property value is retrieved or assigned, respectively.

 Public Property Get VehicleIdNumber() As Double     VehicleIdNumber = dblVehicleIdNumberVal End Property Public Property Let VehicleIdNumber(ByVal Value As Double)     dblVehicleIdNumberVal = Value End Property

You can use this class later on in the chapter to see one or more of these properties in action.

image from book

Creating Methods

As you are aware, methods are actions that can be taken on an object. Methods for custom classes are implemented using public sub procedures and functions.

Using Public Sub Procedures and Functions

To implement a method for a custom class, you simply add a public sub procedure or function to the class itself. You are already familiar with creating new procedures, so creating a custom method will be really easy for you. To add a method called TestMethod to a class module, you simply add the following code:

  Public Sub TestMethod()     'code for the method goes here End Sub 

Now, create the four methods for the clsCar class: Retrieve, Add, Update, and Delete. You may wish to refer to Figure 4-2 to see how the Class Diagram maps to the code you write.

Try It Out-Creating the Methods for the Car Class

image from book
  1. Add the Retrieve method to the clsCar class:

      Public Function Retrieve(ByVal VehicleId As Integer) As Recordset     'Retrieve the detail record for the car from the database     'code to call the data access layer that retrieves the record from     'the database     Debug.Print "clsCar.Retrieve method"     Debug.Print "VehicleID: " & VehicleId & " will be retrieved from the database." End Function 

  2. Add the Add method to the clsCar class:

      Public Sub Add()     'Add the current values in the Car object to the database     'code to call the data access layer that adds the record to the database     Debug.Print "clsCar.Add method"     Debug.Print "New record being added for VehicleId: " & Me.VehicleIdNumber End Sub 

    Tip 

    Did you notice that when you typed Me and a period, all of your properties, class variables, and functions appeared? This command completion feature in Access and other Microsoft programming products is called Microsoft IntelliSense.

  3. Add the Update method to the clsCar class.

      Public Sub Update()     'Update the database with the current contents of the Car object     'Code to call the data access layer that updates the existing     'record in the database     Debug.Print "clsCar.Update method"     Debug.Print "Record being updated for VehicleId: " & Me.VehicleIdNumber End Sub 

  4. Add the Delete method to the clsCar class:

      Public Sub Delete()     'Delete the Car record from the database     'Code to call the data access layer that deletes the record from the     'database. Pass the VehicleId value as a parameter.     Debug.Print "clsCar.Delete method"     Debug.Print "Record being deleted for VehicleId: " & Me.VehicleIdNumber End Sub 

  1. Click the Save button on the toolbar to save your changes to the class.

How It Works

First, you created the Retrieve method of the clsCar class. The Retrieve method is responsible for calling the data access layer to look up a particular car record.

 Public Function Retrieve(ByVal VehicleId As Integer) As Recordset    'Retrieve the detail record for the car    'from the database    'code to call the data access layer that retrieves the record from     'the database

For illustration purposes, the method includes code to print a message to the Immediate Window to let you know that the method executed.

     Debug.Print "clsCar.Retrieve method"     Debug.Print "VehicleID: " & VehicleId & " will be retrieved from the database." End Function

Next, you created the Add method to handle adding a new car record to the database.

 Public Sub Add()     'Add the current values in the Car object to the database     'code to call the data access layer that adds the record to the database

Again, the method includes code to print a message to the Immediate Window to let you know that the method executed.

       Debug.Print "clsCar.Add method"       Debug.Print "New record being added for VehicleId: " & Me.VehicleIdNumber End Sub

The Update and Delete methods are created in similar ways. One or more of these methods will be used in later examples. Now turn your attention to events.

image from book

Creating Events

Events occur in response to an action taken by the user or the system. Custom events can be created in class modules, but they must also be raised (fired) in code or the event will never happen.

Declaring and Raising Events

First, you must declare and raise the event. An event declaration can be added to the General Declarations section of the class module as shown here:

  Public Event EventName(VariableName As DataType) 

After the event has been declared, you add code to a procedure in your class module to raise the event when a certain action happens. Events are raised with the RaiseEvent statement. To see how this works, create an event for the Car class.

Try It Out-Creating an Event for the Car Class

image from book
  1. Declare the event with the PublicEvent statement in the General Declarations section of the clsCar class module.

      Public Event ActionSuccess(strMessage As String) 

  2. Modify the existing Update method in clsCar to include the following additional code:

     Public Sub Update()     'Update the database with the current contents of the Car object     'Code to call the data access layer that updates the existing     'record in the database     Debug.Print "clsCar.Update method"     Debug.Print "Record being updated for VehicleId: " & Me.VehicleIdNumber     'raise the ActionSuccess event     RaiseEvent ActionSuccess("Updates to existing record saved successfully!") End Function 

How It Works

First, the event was declared in the class module by using the Public Event statement. Next, code was added to the existing Update method to raise the event. At this point, the code will not result in any action when the event fires. To create the action, take the following additional steps.

image from book

Creating the Event Sub Procedure or Function

You must write code that executes when an event is raised. In Chapter 3, you had to create event procedures to specify what should happen when an event occurs. You now use the same process for custom objects.

In the General Declarations section of the object where you wish to handle the event, you declare the object variable for the class that causes the event using the WithEvents keyword:

  Dim WithEvents objCar As clsCar 

After the object has been declared using WithEvents, the Visual Basic Editor displays the object in the list of objects and displays the event in the procedure drop-down list, just as it would for any other object. You can select the object and event from the list, and the code template is automatically specified. You then add the code that you want to run when the event occurs.

  Private Sub objCar_ActionSuccess(strMessage As String) 'code to execute when event occurs goes here End Sub 

You will actually create the event in the sample database momentarily, but first I want to cover a few other topics necessary to write the sample code to handle the event.

Using the Class

After writing the code for the class module, you can use the class from other places in your application.

Instantiating the Class

To use a class module in your application, you first must use the Dim statement to declare the class and a Set statement to create a new instance of the class, as shown here:

  Dim objCar As clsCar Set objCar = New clsCar 

As you will see in a moment, the preceding lines of code do not have to be contained in the same procedure. After the class has been instantiated, it becomes an object in memory.

Initialize and Terminate Events

Each class has Initialize and Terminate events that can be used. These events should be used when you want certain code to run each time the class is created or destroyed. Now return to the hypothetical Wrox Auto Sales application example and try out the properties, methods, and event of the clsCar class.

Try It Out-Using the Properties, Methods, and Events of the Car Class

image from book
  1. Return to the database window and create a new form. To do so, select the Create ribbon, and then New Form. Switch to design view by selecting the Home ribbon, and then Design View from the View drop-down list. Use the controls on Design ribbon to select and draw one text box and four command buttons on the new form, as shown in Figure 4-4. Click cancel on the wizards that open as you draw the buttons on the form, as you do not need them.

    image from book
    Figure 4-4

  2. Change the Name property of the text box to txtVehicleId. Change the Name property of the label to lblVehicleId and the Caption property to Vehicle Id:. Change the Name properties of the command buttons to cmdLookup, cmdSave, cmdAddNew, and cmdDelete, respectively. Change the Caption properties of the command buttons to Lookup, Save, Add New, and Delete, respectively. Figure 4-5 shows how the form should look at this point.

    image from book
    Figure 4-5

  3. Select the Save button on the Toolbar of the Form Designer to save the form. Name the form frmCarDetails.

  1. From the Properties dialog box of the Form, select the On Load event on the Events tab. Use the Code Builder to add an empty event procedure for the On Load event, as shown here:

      Private Sub Form_Load() End Sub 

  2. For the moment, leave the Form_Load event empty and add the following code to the General Declarations section of the frmCarDetails class:

      Dim WithEvents objCar As clsCar 

  3. Return to the Form_Load event and add the following code:

      Private Sub Form_Load() 'create a new instance of the car class to use while the form is open Set objCar = New clsCar End Sub 

  4. Add the following Click event to the frmCarDetails class:

      Private Sub cmdLookup_Click() 'set the value of the VehicleId in the car object 'to the current value in the text box on the form objCar.VehicleIdNumber = txtVehicleId 'call the Retrieve method objCar.Retrieve (objCar.VehicleIdNumber) End Sub 

  5. Add the following Save event to the frmCarDetails class:

      Private Sub cmdSave_Click() 'add the values in the car object to the database objCar.Update End Sub 

  6. Add the following ActionSuccess event to the frmCarDetails class:

      Private Sub objCar_ActionSuccess(strMessage As String)    'display the message to the user    MsgBox strMessage End Sub 

  1. Save all your changes by clicking the Save button on the Visual Basic Editor. Also, return to your form and click the Save button on the Form Designer toolbar.

  2. Run the form by selecting the Home ribbon, and then Form View from the View area. Enter a value for the VehicleId text box on the form, as shown in Figure 4-6.

    image from book
    Figure 4-6

  3. Click the Lookup button. The Immediate Window of the Visual Basic Editor will display information similar to that shown in Figure 4-7.

    image from book
    Figure 4-7

  4. Return to the form and click the command button labeled Save. The Immediate Window of the Visual Basic Editor will display information similar to that shown in Figure 4-8.

    image from book
    Figure 4-8

    Tip 

    If the Immediate Window is not open, then go to the View Menu and select Immediate.

  5. A message box similar to the one shown in Figure 4-9 is then displayed.

    image from book
    Figure 4-9

How It Works

You started by creating a new form called frmCarDetails and adding a text box control and four command buttons. The text box control is used to enter and display the Vehicle ID, and the four command buttons are used for Lookup, Save, Add New, and Delete functionality. After modifying various properties for the controls, you declared an objCar variable to store an instance of the clsCar class. Notice that the WithEvents keyword is used as part of the declaration so that the form can detect the custom event when it occurs.

 Dim WithEvents objCar As clsCar

As shown in Figure 4-10, as you typed the declaration for the object, the name of the clsCar class that you created appeared in the drop-down list along with existing objects that you did not create.

image from book
Figure 4-10

The code to instantiate the class was then added to the Form_Load event of the frmCarDetails class.

 Private Sub Form_Load() 'create a new instance of the car class to use while the form is open Set objCar = New clsCar End Sub

You then added code for the Click event of the cmdLookup button of the frmCarDetails class. In this event, when the user clicks the Lookup button on the form, the VehicleIdNumber property of the objCar class is assigned the value from the text box on the form. The Retrieve method is then called.

 Private Sub cmdLookup_Click() 'set the value of the VehicleId in the car object 'to the current value in the text box on the form objCar.VehicleIdNumber = txtVehicleId 'call the Retrieve method objCar.Retrieve (objCar.VehicleIdNumber) End Sub

As you entered the code to set the VehicleIdNumber property, a drop-down list (as shown in Figure 4-11) appeared and displayed all the properties and methods for your custom class. Pretty cool, huh? Those are properties and methods that you created.

image from book
Figure 4-11

You then added the Save event to the frmCarDetails class to call the Update method when you click the Save button on the form.

 Private Sub cmdSave_Click() 'add the values in the car object to the database objCar.Update End Sub

Next, you added the ActionSuccess event to the frmCarDetails class. This is a custom event that is raised in the clsCar class from the Update method. After the event is raised, the following code runs:

 Private Sub objCar_ActionSuccess(strMessage As String) 'display the message to the user MsgBox strMessage End Sub

Next, you ran the form, entered a value for the VehicleId text box on the form, and selected the Lookup button. The Immediate Window then displayed the messages indicating that the Retrieve method of the clsCar object had executed. After you clicked the Save button on the form, the Immediate Window displayed messages indicating the Update method had executed, and displayed a message box indicating that the record was successfully updated. Remember that this is the code you previously added to the Update method to raise the custom event ActionSuccess. In just these few steps, you not only tested the properties, methods, and event for your custom object, but you also used several properties, methods, and events for the existing objects.

Tip 

Note that the example used for the frmCarDetails form illustrated just a partial set of the controls that would be included on the production version of the Manage Cars screen. Only the VehicleIdNumber field was used for sake of simplicity.

image from book

Advanced Techniques

Now that you have a basic idea of how to use class modules to create your own objects with properties, methods, and events, you can delve into some advanced techniques.

Creating Multiple Instances of the Class

You already learned how to declare and create an instance of a class using the Dim and Set statements. The following example illustrates how you can create multiple instances of the same class when adding this code to the class module for frmCarDetails.

  Public Sub TestMultipleInstances() 'declare both clsCar objects Dim objCar1 As clsCar Dim objCar2 As clsCar 'instantiate new instances for each Set objCar1 = New clsCar Set objCar2 = New clsCar 'set the VehicleId property for the first instance 'of clsCar and then call the previously created 'update method as an example objCar1.VehicleIdNumber = "98765" objCar1.Update 'set the VehicleId property for the second instance 'of clsCar and then call the previously created 'update method as an example objCar2.VehicleIdNumber = "12345" objCar2.Update End Sub 

Notice how two different clsCar objects are declared and instantiated. The VehicleIdNumber property of each instance of the class is assigned, and the Update method of each instance of the class is called.

As shown in Figure 4-12, the Immediate Window displays the messages generated from the Update method indicating that the record was being updated for each respective instance of the class.

image from book
Figure 4-12

Creating Class Hierarchies

Classes can be related to each other in parent-child class relationships called class hierarchies. Suppose that you have an object called Orders that contains overall details about a particular order placed for products, and you also have an object called OrderDetails that contains details about a particular individual product within that order. The Orders object can contain multiple OrderDetails objects. To relate the Orders object to the OrderDetails object, place a declaration of the child class in the General Declarations section of the Orders object, as shown here:

  Public ItemDetails As OrderDetails 

You then use the Set statement to instantiate the OrderDetails class just as you do for the Orders class.

Working with Enumerated Types

Enumerated types can be used when you want to require a property value to be limited to a specified list of constants. Suppose that you have the following code in the General Declarations section of a clsCar object:

  Public Enum SpecialFeaturesList     SunRoof     MoonRoof     NavigationSystem     IntegratedPhone     Other End Enum 

In the property declarations, you see the SpecialFeaturesList enumerated type in the list of objects available, as shown in Figure 4-13.

image from book
Figure 4-13

The Property Get and Property Let procedures using the SpecialFeaturesList enumeration look like this:

  Public Property Get SpecialFeatures() As SpecialFeaturesList       SpecialFeatures = SpecialFeaturesVal End Property Public Property Let SpecialFeatures(ByVal Value As SpecialFeaturesList)       SpecialFeaturesVal = Value End Property 

Now anytime you try to set that property using an assignment statement, you are limited to those values specified in the enumeration declaration, as shown in Figure 4-14.

image from book
Figure 4-14

Inheritance Using Implements Keyword

Access allows for a type of inheritance called interface inheritance. Interface inheritance allows you to adopt the properties and methods of another object. This feature is implemented using the implements keyword, as shown here:

  Implements clsCar 

If the preceding code is placed in the General Declarations section of a new class module, you will see the clsCar object in the Object drop-down list, as well as the properties and methods of the clsCar object. You can then select a particular property or method and write the code for that property or method. This is a big drawback to interface inheritance - it requires you to write the code to implement those properties and methods. True inheritance (supported in more advanced programming languages, such as Visual C++, Visual Studio .NET, and Visual Studio Tools for Office) enables you to inherit all the properties and methods from another class, including all the code that goes with it.




Beginning Access 2007 VBA
Beginning Access 2007 VBA
ISBN: 0470046848
EAN: 2147483647
Year: 2004
Pages: 143

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net