Binding Object, BindingCollection Object Example

The example uses the BindingCollection object to bind a data source to two TextBox controls. The example first opens an ADODB recordset object, then sets the DataSource property of the BindingCollection to the recordset. The code then adds two Binding objects to the collection, thereby binding two TextBox controls to different fields of the recordset.

To try the example, in the References dialog box set a reference to the Microsoft Data Binding Collection. In the same dialog box, set a reference to the Microsoft ActiveX Data Objects Library. Draw two TextBox controls on a Form, and paste the code into the Declarations section. Press F5, and click the form to advance through the recordset.

Option Explicit
Private colBndNwind As New BindingCollection
Private rsNwind As New ADODB.Recordset
Private cn As New ADODB.Connection

Private Sub Form_Load()

   ' Set the Connection object parameters.   
   With cn
      ' The following connection may or may not work on your computer.
      ' Alter it to find the Nwind.mdb file, which is included with
      ' Visual Basic.
      .Provider = "Microsoft.Jet.OLEDB.3.51"
      .Open "C:\Program Files\DevStudio\VB\Nwind.mdb"
   End With
   
   ' Open the recordset object. 
   rsNwind.Open "Select * From Products", cn
   
   ' Set the DataSource of the Bindings collection to the recordset.
   Set colBndNwind.DataSource = rsNwind
   
   ' Add to the Bindings collection.
   With colBndNwind
      .Add Text1, "Text", "ProductName", , "product"
      .Add Text2, "Text", "SupplierID", , "ID"
   End With

   ' Print the properties of the objects in the collection.
   Dim bndObj As Binding
   For Each bndObj In colBndNwind
      Debug.Print "DataField", "PropertyName", "Key"
      Debug.Print bndObj.DataField, bndObj.PropertyName, bndObj.Key
      Debug.Print
   Next
End Sub

Private Sub Form_Click()
   ' Move to the next record by clicking the form.
   rsNwind.MoveNext
End Sub