The Basics > Configuring Columns at Run Time > Referencing column objects |
When a column is added to or removed from a grid, the associated Column object is added to or removed from the grid's Columns collection. This may cause a change in the index numbers of the existing columns, making it very inconvenient to reference columns numerically. For this reason, True DBGrid also allows you to reference columns using either the DataField or Caption strings. Thus, the following references are identical:
Example Title |
Copy Code
|
---|---|
' Reference by the Column index. TDBGrid1.Columns(n) ' Reference by the DataField name. TDBGrid1.Columns("LAST") ' Reference by the Caption string. TDBGrid1.Columns("Last Name") |
Referencing column objects by DataField or Caption is not case-sensitive. TDBGrid1.Columns("LAST") refers to the same column as TDBGrid1.Columns("last").
When you reference a Column object and its properties at run time, Visual Basic creates an instance of the object. For example, if you duplicate certain properties of a column:
Example Title |
Copy Code
|
---|---|
TDBGrid1.Columns("First").Width = _ TDBGrid1.Columns("Last").Width TDBGrid1.Columns("First").Alignment = _ TDBGrid1.Columns("Last").Alignment TDBGrid1.Columns("First").AllowSizing = _ TDBGrid1.Columns("Last").AllowSizing |
The Columns("First") and Columns("Last") objects will each be created and discarded three times in the preceding example. The same results are achieved more efficiently by creating object variables that refer to these columns:
Example Title |
Copy Code
|
---|---|
' Declare Column objects. Dim FirstCol As TrueDBGrid80.Column Dim LastCol As TrueDBGrid80.Column ' Reference First and Last Column objects. Set FirstCol = TDBGrid1.Columns("First") Set LastCol = TDBGrid1.Columns("Last") ' Copy properties from Last to First. FirstCol.Width = LastCol.Width FirstCol.Alignment = LastCol.Alignment FirstCol.AllowSizing = LastCol.AllowSizing |
The same technique can be applied to other objects in Visual Basic. For more details, see Object Model.