The COM Course - Part 2, Page 5
Let's get your class up-and-running:
- Press F5 to run your program
- If prompted for further information, select 'Wait for Components to Start', then click OK
Your class is now 'alive' but waiting for other programs to use its functionality.
- Launch another instance of Visual Basic
- Create a new 'Standard EXE' project
- Click 'Project', 'References'
Have a scroll around the list. These are all extra widgets you can add to your project.
- Check 'Northwind' in the list
Northwind is your ActiveX project!
- Click OK
Now let's add a little code to activate your project:
- Add a Command Button to Form1
- Type in the following:
Dim Test As CustomersSet Test = New CustomersMsgBox Test.CustomerIDSet Test = Nothing
This code creates a new Customers object. Then the CustomerID is displayed in a message box. Finally, the Test object is set to Nothing, closing it down.
- Hit F5 to run your test application
Top Tip: If you're getting 'invalid reference' error messages when running your application, something definitely boobed. Follow these steps to 'reset' (1) remove the Northwind reference in your test project, (2) restart your Northwind project, (3) add the reference to Northwind back to your test project, then try again.
- Click your Command Button
It may take a few seconds to start-up after all, it's opening a database connection and so on but after that initial delay, all calls will perform at lightening speed. You should get a message box displayed containing the name 'ALFKI'.
- Stop your test application
Now, let's figure out exactly what's happening behind the scenes.
- Move your cursor to the line of code starting MsgBox Test.CustomerID
- Press F9
A red line will mark the code. When this code runs, it will stop here, at the 'breakpoint'. Pressing F8 will run that line of code and move onto the next.
- Press F5 to run your test application (again)
- Click your Command Button
The code should stop on your MsgBox command.
- Press F8 and slowly step through each line of code
You should be automatically switched backwards and forwards between both instances of Visual Basic. This shows you exactly what happens when you access the various properties.
Notice anything interesting?
- When finished, stop your test application
Let's continue testing your program. This time, we'll set the CustomerID instead of merely retrieving the value.
- Change the Command Button code to:
Dim Test As CustomersSet Test = New CustomersTest.CustomerID = "KARLY"Test.UpdateMsgBox Test.CustomerIDSet Test = Nothing
This code sets the 'CustomerID' field, then Updates the recordset. Finally, it displays the CustomerID property, which should be set to 'KARLY'.
- If you wish, press F9 to highlight the "Test.CustomerID =" line of code then step through once more with the F8 button to see how it all works
And that's it! Congratulations on successfully creating and testing your raw database class!
As an experiment, why not try setting the customer ID property to a string greater than five characters in length? You should get back an error message. Try adding regular error handling code to deal with this. See what happens!
Next up, let's take your current database class and improve it.### Completing our Class ###
Now we want to add even more features to our class extra properties, a few methods and perhaps even an event or two.
I'm not going to walk you through every part of this code, you should be able to figure it out. So just take a look, read the comments, copy-and-paste and let's continue:
- Replace your class code with this updated code:
Dim WithEvents rs As RecordsetPublic Event RecordsetMove()Private Sub Class_Initialize() Set rs = New Recordset rs.ActiveConnection = "Provider=Microsoft." & _ "Jet.OLEDB.4.0;Data Source=C:\Program Files\" & _ "Microsoft Visual Studio\VB98\Nwind.mdb;" & _ "Persist Security Info=False" rs.Open "select * from customers", , adOpenKeyset, adLockOptimisticEnd SubPrivate Sub Class_Terminate() rs.Close Set rs = NothingEnd SubPublic 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, by running ' Err.Raise vbObjectError + OurErrorNumber 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 PropertyPublic Property Get CompanyName() As Variant CompanyName = rs("CompanyName")End PropertyPublic Property Let CompanyName(ByVal NewValue As Variant) rs("CompanyName") = NewValueEnd PropertyPublic Property Get ContactName() As Variant ContactName = rs("ContactName")End PropertyPublic Property Let ContactName(ByVal NewValue As Variant) rs("ContactName") = NewValueEnd PropertyPublic Property Get ContactTitle() As Variant ContactTitle = rs("ContactTitle")End PropertyPublic Property Let ContactTitle(ByVal NewValue As Variant) rs("ContactTitle") = NewValueEnd PropertyPublic Property Get Address() As Variant Address = rs("Address")End PropertyPublic Property Let Address(ByVal NewValue As Variant) rs("Address") = NewValueEnd PropertyPublic Property Get City() As Variant City = rs("City")End PropertyPublic Property Let City(ByVal NewValue As Variant) rs("City") = NewValueEnd PropertyPublic Property Get Region() As Variant Region = rs("Region")End PropertyPublic Property Let Region(ByVal NewValue As Variant) rs("Region") = NewValueEnd PropertyPublic Property Get PostalCode() As Variant PostalCode = rs("PostalCode")End PropertyPublic Property Let PostalCode(ByVal NewValue As Variant) rs("PostalCode") = NewValueEnd PropertyPublic Property Get Country() As Variant Country = rs("Country")End PropertyPublic Property Let Country(ByVal NewValue As Variant) rs("Country") = NewValueEnd PropertyPublic Property Get Phone() As Variant Phone = rs("Phone")End PropertyPublic Property Let Phone(ByVal NewValue As Variant) rs("Phone") = NewValueEnd PropertyPublic Property Get Fax() As Variant Fax = rs("Fax")End PropertyPublic Property Let Fax(ByVal NewValue As Variant) rs("Fax") = NewValueEnd PropertyPublic Sub AddNew() rs.AddNewEnd SubPublic Sub Update() rs.UpdateEnd SubPublic Sub CancelUpdate() If rs.EditMode = adEditInProgress Or _rs.EditMode = adEditAdd Then rs.CancelUpdate End IfEnd SubPublic Sub MoveNext() rs.MoveNext End SubPublic Sub MovePrevious() rs.MovePrevious End SubPublic Sub MoveFirst() rs.MoveFirstEnd SubPublic Sub MoveLast() rs.MoveLastEnd SubPublic Function FindByCustomerID(CustomerID As String) As Boolean ' Uses the Find method to locate customers ' with a matching CustomerID. ' Returns True value is customer(s) found Dim varBookmark As Variant rs.MoveFirst rs.Find ("CustomerID='" & CustomerID & "'") If rs.EOF = True Then FindByCustomerID = False rs.Bookmark = varBookmark Else FindByCustomerID = True End IfEnd FunctionPublic Property Get EOF() As Boolean ' Example of a read-only property ' No Property Lets here EOF = rs.EOFEnd PropertyPublic Property Get BOF() As Boolean ' Another example of a read-only property BOF = rs.BOFEnd PropertyPrivate Sub rs_MoveComplete(ByVal adReason As ADODB.EventReasonEnum, _ByVal pError As ADODB.Error, adStatus As ADODB.EventStatusEnum, _ByVal pRecordset As ADODB.Recordset) ' Reacts to the recordset MoveComplete ' method - raises event with each move RaiseEvent RecordsetMoveEnd Sub
Top Tip: So far in this tutorial, we've only added code to one class. However you can easily add more classes to your projects, by clicking 'Project', 'Add Class'. You can even make these classes work together by utilising 'collections'. In a situation like ours however, you may want to consider using one class per table.