Visual Basic Concepts
The DataGrid control has several methods and menu commands that affect both the layout of the grid, and how the control is bound to data. These methods and commands include:
One feature of the DataGrid is its design-time features. You can configure a data source, such as the ADO Data control, connect it to the DataGrid control, invoke the Retrieve Structure menu command, and customize the layout of the grid.
The grid is now configured with a default layout: one column per field in the recordset, and each column set to the same width.
If you have edited the layout as shown above, you can now use the HoldFields and ClearFields methods to either preserve or cancel the layout when the Rebind method is invoked. This only becomes apparent when the recordset itself has been altered. In that case, if the HoldFields method has been invoked, the layout is preserved, but blank columns are substituted for missing fields. On the other hand, if the ClearFields method is invoked, all missing fields are deleted, and only the fields present in the altered recordset are displayed. A sample is shown below.
To show the effects of HoldFields and ClearFields
See the topic Creating the Northwind OLE DB Data Link for an example.
Option Explicit
Private Sub Form_Load()
' Reset the captions for the controls and set the CheckBox
' Value to vbChecked.
Command1.Caption = "Rebind"
Check1.Caption = "Hold/Clear Fields"
Check1.Value = vbChecked ' Set to HoldFields.
End Sub
Private Sub Command1_Click()
' The ReDoADODC sub reconfigures the ADO Data Control to deliver an
' altered recordset.
ReDoADODC
' Use either HoldFields or the ClearFields method depending on the
' value of the checkbox.
If Check1.Value = vbChecked Then
With DataGrid1
.HoldFields
.ReBind
End With
Else ' unchecked means Clearfields.
With DataGrid1
.ClearFields
.ReBind
End With
End If
End Sub
Private Sub ReDoADODC()
With Adodc1
.CommandType = adCmdText
.RecordSource = "SELECT ProductName, UnitPrice FROM Products"
.Refresh
End With
End Sub
When the project runs, the DataGrid should be filled with the data from the Northwind database, and its layout should be as you designed it. By default, the CheckBox is set to the "Holdfields" setting.
Notice that several columns are now blank.
Notice that only the layout of the grid is now set according to the number of columns (2) in the recordset.
The grid will revert to the previous layout even though the HoldFields method has been invoked. This is because the control doesn't yet know what the custom layout is.
The grid will now retain the previous layout.
The grid will display only the two columns with default widths.