Format Objects Tutorial

See Also

The following procedure gives you a brief overview of using format objects with bound controls attached to the ADO Data Control. The example uses the Nwind.mdb sample database provided with Visual Basic.

Note that although this example uses the ADO Data Control, format objects can be used with any data source.

Using the ADO Data Control with Format Objects

  1. Create an OLEDB Data Source for the Northwind database, named "Northwind".

    If a data source has not been created, follow the steps in Creating the Northwind OLEDB Data Source.

  2. From the Project menu, set references to the Microsoft Data Formatting Object Library and the Microsoft Data Binding Collection.

  3. On the Project menu click Components, and check the ADO Data Control.

  4. Add the ADO Data control and three TextBox controls to a form.

  5. Set property values as shown in the following table.
    Object Property Setting
    ADO control ConnectionString northwind.mdl
    ADO control RecordSource select * from Employees
    Text1 control DataSource ADODC1
    Text1 control DataField LastName
    Text2 control DataSource ADODC1
    Text2 control DataField HireDate
    Text3 control DataSource ADODC1
    Text3 control DataField Extension

  6. Add the following declarations to the form.
    ' Binds textboxes to the ADO control.
    Dim bc As New BindingCollection
    
    ' We'll add code to the Format event on this object.
    Dim WithEvents f1 as StdDataFormat
    Dim WithEvents f2 As StdDataFormat
    

    Declaring f2 with the WithEvents statement exposes the object's events. Step 8 shows code using the Format event to work on data as it is passed back and forth between the database and bound object.

  7. Add the following code to the form's Load event.
    ' Connect the BindingCollection object to the datasource.
    Set bc.DataSource = ADODC1
    
    'set a long date format string
    Set f1 = New StdDataFormat
    f1.Type = fmtCustom
    f1.Format = "long date"
    ' Use the BindingCollection object to bind the 2nd text box.
    bc.Add Text2, "text", "hiredate", f1
    
    'set a currency format string
    Set f2 = New StdDataFormat
    f2.Type = fmtCustom
    f2.Format = "$0.00"
    ' Use the BindingCollection object to bind the 3rd text box.
    Set bc.DataSource = ADODC1
    bc.Add Text3, "text", "extension", f2
    
  8. Add the following code to the f2 object's Format event.
    If DataValue.Value < 3000 Then
    Text3.ForeColor = vbRed
    Else
    Text3.ForeColor = vbBlack
    End If
    
  9. Run the project and experiment with the ADO Data control.