Refer to Columns in a DBGrid Control

Refer to Columns in a DBGrid Control

Columns in a DBGrid control are bound to database fields. However, the index number of a column doesn’t tell you which field it represents. Therefore, referring to DBGrid1.Columns(0).Value is not very descriptive. It’s better to introduce variables with clear names, which are bound to specific columns. In the declarations section of the form, for example, the code reads:

 Dim ColOrder_ID As ColumnDim ColArticle_ID As ColumnDim ColAmount As Column

In the Form_Load event of the form, the code reads:With DBGrid1 Set ColOrder_ID = .Columns(0) Set ColArticle_ID = .Columns(1) Set ColAmount = .Columns(2)End With It’s no longer necessary to refer to DBGrid1.Columns(0).Value, for example, but you can use ColOrder_ID.Value instead. ColOrder_ID is, of course, the same as DBGrid1.Columns(0). If any property value of DBGrid1.Columns(0) changes, the same property value of ColOrder_ID changes accordingly, and vice versa.Later on, when you insert a database field into the grid, you change only the index numbers of the columns in the code of the Form_Load event.


Share the Post: