A Beginner's Guide to COM Interfaces
I know what you are saying now, why on Earth is this useful? Well, instead of spending another ten pages explaining it, here is a little example.
Open VB and create a new Standard EXE Project. Click Project, Add Class Module. Repeat this. Also Click Project, References. Select Microsoft DAO 3.51 Object Library. Now you should have two class modules. Rename the first IDataObject and the second CPerson. To the IDataObject add the following code:
Option Explicit Public IsChanged As Boolean Public Sub Save() End Sub Public Sub GetInfo() End Sub
Open the second class, CPerson and add the following code:
Option Explicit Implements IDataObject Private m_db As Database Private m_rs As Recordset Private m_lngID As Long Private m_strName As String Private m_strAddress As String Private m_blnChanged As Boolean Private Sub Class_Initialize() Set m_db = OpenDatabase(App.Path & "\people.mdb") End Sub Private Sub Class_Terminate() m_rs.Close m_db.Close Set m_rs = Nothing Set m_db = Nothing End Sub Private Sub IDataObject_GetInfo() If ID = 0 Then Err.Raise vbObjectError, "CPerson", "A valid ID must be set before attempting to retrieve data." End If Set m_rs = m_db.OpenRecordset("SELECT * FROM People WHERE ID =" & ID) Name = m_rs.Fields("Name").Value Address = m_rs.Fields("Address").Value End Sub Private Property Let IDataObject_IsChanged(ByVal RHS As Boolean) m_blnChanged = RHS End Property Private Property Get IDataObject_IsChanged() As Boolean IDataObject_IsChanged = m_blnChanged End Property Private Sub IDataObject_Save() If ID <> 0 Then m_rs.Edit Else m_rs.AddNew End If m_rs.Fields("Name").Value = Name m_rs.Fields("Address").Value = Address m_rs.Update End Sub Public Property Get ID() As Long ID = m_lngID End Property Public Property Let ID(ByVal NewID As Long) m_lngID = NewID End Property Public Property Get Name() As String Name = m_strName End Property Public Property Let Name(ByVal NewName As String) m_strName = NewName End Property Public Property Get Address() As String Address = m_strAddress End Property Public Property Let Address(ByVal NewAddr As String) m_strAddress = NewAddr End Property
As you can see we are using a database to store the CPerson information. We have used DAO 3.5 for this although you can modify it to whatever data access you want. Notice that all the methods and properties have been implemented. This is neccessary when implementing an interface otherwise you will run into errors. Take a closer look at the IDataObject_Save method. If the ID is 0, then it is not a current record and therefore a new one needs to be added. Also take a look at the IDataObject_GetInfo method. As with all code in class modules, you should always raise the error and let the module / form / usercontrol handle the error.
Page 4 of 6