Working with Columns

You can dynamically change the data displayed in the DataGrid control by changing the DataSource property. For example, you can display a different table from the same database. If you do so, the DataGrid control will display the data with only default properties.

Adding, Deleting, or Hiding Columns

You can programmatically add, delete, or hide Columns by using the properties and methods of the Columns collection and the Column object.

Adding and Deleting a Column

To add a column at run time, use the Add method. If you first declare a variable and assign the new object to the variable, you can set various properties with concise code.

Private Sub AddColumn()
   ' Add a column in the rightmost position. Then set its Visible, Width, 
   ' Caption, and Alignment properties. The DataField property specifies 
   ' which field the column will be bound to.
   Dim c As Column
   Set c = DataGrid1.Columns.Add(DataGrid1.Columns.Count)
   With c
      .Visible = True
      .Width = 1000
      .Caption = "My New Column"
      .DataField = Adodc1.Recordset.Fields("ProductName").Name
      .Alignment = dbgRight
   End With
End Sub

You can delete any column by using the Remove method. Be sure to specify which column using the ColIndex argument. The following code will remove the clicked column.

Private Sub DataGrid1_HeadClick(ByVal ColIndex As Integer)
   DataGrid1.Columns.Remove ColIndex
End Sub

Hiding a Column

You can hide any column by setting its Visible property to False. This is especially useful when you want to limit columns that the user can view or edit. The example below simply iterates through the Columns collection, hiding all but a few columns.

Private Sub HideColumns()
   ' Use the DataField property to determine which column is being 
   ' tested. Show only three columns: ProductName, UnitPrice, and 
   ' UnitsInStock. 
   
   Dim c As Column
   For Each c In DataGrid1.Columns
      Select Case c.DataField
      Case "ProductName"
         c.Visible = True
      Case "UnitPrice"
         c.Visible = True
      Case "UnitsInStock"
         c.Visible = True
         c.Caption = "In Stock" ' Change the column header.
      Case Else ' Hide all other columns.
         c.Visible = False
      End Select
   Next c
End Sub