Microsoft Access 2010 Bible

(Rick Simeone) #1

Part IV: Professional Database Development


980


frmProductUnbound makes several property assignments from the form’s Load event proce-
dure. The following code listing shows the entire Form_Load sub from frmProductUnbound.
Notice how the code builds the recordset, makes the property assignments, and fills the text boxes
on the form through the SetObjectProperties and FillForm procedures.

Private Sub Form_Load()
Set Product = New clsProduct1
Set rs = CurrentDb.OpenRecordset(“tblProducts”)
If rs.RecordCount > 0 Then
Call SetObjectProperties
Call FillForm
End If
End Sub

Similarly, selling a product involves using the object’s Sell method. The code below shows how a
form might use the Sell method. Notice that the code passes a parameter: txtNumberToSell.
The user has entered the number of items to sell into a text box named txtNumberToSell. That
value becomes the UnitsSold argument for the Sell method I mentioned in the “Looking at a
simple class module” section, earlier in this chapter.

Private Sub cmdSell_Click()
Product.Sell txtNumberToSell
Call FillForm
End Sub ‘cmdSell_Click

The FillForm procedure is called to refresh the form’s contents after the Sell method executes.

Creating bulletproof property procedures
In many cases, assigning an invalid value to a property results in a runtime error or other bug. If
you’re lucky, the invalid value causes the application to halt and display an error message to the
user. It’s much worse to have the application continue operating as if nothing is wrong when, in
fact, the class module is working with invalid data. The best situation is when the class module
itself validates property values as they’re assigned, instead of waiting until the properties are used
by forms, reports, and code in the application.

For example, consider a banking application that calculates exchange rates for foreign currency
deposited in the bank’s vault. A class module is the ideal vehicle for handling foreign currency
exchange calculations. Keeping these calculations in a class module isolates these complicated rou-
tines from the rest of the application and makes it easy to maintain the calculations as currency
values fluctuate. And, because class modules support IntelliSense, it’s much easier to work with
objects defined by class modules than public procedures stored in standard modules.

Ideally, the exchange rate class module wouldn’t accept invalid exchange ratios or would check the
exchange ratios that the user inputs at runtime. Perhaps the class module could check online
sources such as The Wall Street Journal or other financial publications to verify that the data the
user input is correct.
Free download pdf