The COM Course - Part 2
Next, I'd like to add a property that allows our user to retrieve the Customer ID. Here's a piece of sample code I created earlier:
Public Property Get CustomerID() As String CustomerID = rs("CustomerID")End PropertyPublic Property Let CustomerID(NewValue As String) rs("CustomerID") = NewValueEnd Property
Do you understand what's happening here? The Property Get simply 'returns' whatever is in the 'CustomerID' field. This allows our end user to retrieve the property. The Property Let accepts a new value and sets the 'CustomerID' field to that value.
In other words, there are two parts to a property. The 'getting' and the 'letting'. In fact, there's also another one - 'setting' but that's for a different day. Missing either the Get or the Let out will make the property either write- or read-only.
The power here is that we can check for certain things in these property procedures. For example, to call the Property Let here, the user could do something like:
ObjectName.CustomerID = "HALFI"
When this runs, it calls the Property Let, passing 'HALFI' as the NewValue string. I then set the 'CustomerID' field equal to NewValue. But looking at the Northwind database, I can see that the 'CustomerID' field is limited to just five characters. So if someone did something like this:
ObjectName.CustomerID = "HALFISTORE"
... then we'd get database errors. We could deal with this via database error handling, yes. But we could also check the length of NewValue in code. If it's longer than five characters, you could either just snip the first five letters, ignore the new value altogether - or 'raise' an error. We're going to check for the length and if it's too long, I'll be all-cruel and raise an error. Hehe! <Evil grin goes here>
- Add this code to your class:
Public Property Get CustomerID() As String CustomerID = rs("CustomerID")End PropertyPublic Property Let CustomerID(NewValue As String) ' If the length of NewValue is greater than five If Len(NewValue) > 5 Then ' ... then raise an error to the program ' using this class! Err.Raise vbObjectError + 1, "CustomerID", _ "Customer ID can only be up to five " & _ "characters long!" Else ' ... otherwise, change the field value rs("CustomerID") = NewValue End IfEnd Property
Brilliant! We've just got time for one more method before finishing this section:
- Add the following code to your class:
Public Sub Update() rs.UpdateEnd Sub
When somebody runs the Update method, it simply fires the Update method of our recordset object. Simple.
Next up, we're going to test both this property and method with a mini sample application, plus use a special trick to follow what happens between both your class and test program.
Page 4 of 9
This article was originally published on November 20, 2002