In this section, we’ll walk step-by-step through the process of creating a data-aware class that acts as a data consumer. The previous section, "Creating a Data Source," demonstrates how to create a data source to which a data consumer can be bound. This example shows how to create a data consumer class and bind it to the data source created in the previous section.
The code examples in this section are taken from the Data-aware Classes (Dataware.vbp) sample. You'll find this application in the Samples directory.
This example demonstrates how to create a data consumer class and bind it to a data source class. The example uses the MySource class created in the "Creating a Data Source" topic.
Note If you haven’t previously completed the "Creating a Data Source" example this project won’t exist. You can also find a completed version of the Dataware.vbp project in the Samples directory.
Property | Setting |
Name | MyConsumer |
DataBindingBehavior | vbSimpleBound |
Option Explicit
Private mDirectory As String
Public Property Get DirName() As String
DirName = mDirectory
End Property
Public Property Let DirName(mNewDir As String)
mDirectory = mNewDir
' Display the new value in the Immediate window.
Debug.Print mDirectory
End Property
Since MySource is a nonvisual class, we need to use a Debug.Print statement in the Property Let procedure to prove that it’s retrieving new values from the data source.
Option Explicit
Private objSource As MySource
Private objBindingCollection As BindingCollection
Private objConsumer As MyConsumer
The new line of code adds a reference to our consumer class.
Private Sub Form_Load()
Set objSource = New MySource
Set objBindingCollection = New BindingCollection
Set objConsumer = New MyConsumer
' Assign the source class to the Binding
' Collection’s DataSource property.
Set objBindingCollection.DataSource = objSource
' Add a binding.
objBindingCollection.Add txtConsumer, "Text", "Directory"
objBindingCollection.Add objConsumer, "DirName", "Directory"
The new code creates an instance of the consumer class and adds it to the Binding Collection, binding the DirName property of the consumer to the Directory field of the data source.
As you click the Cycle button, the directory names provided by MySource will appear in both the TextBox and the Immediate window, proving that MyConsumer is bound to MySource.