In this column, we have a detailed look at the TDBGrid component.
With a DBGrid you visualize the contents of a DataSet. The DBGrid also lets you edit, add and delete records, and it lets you scroll and navigate.
This article focuses on the use of the TClientDataSet component, mapped to a local file.
A DBGrid has a Columns property. Each Column has properties that define how the column will look like.
By default, the grid has no persistent column objects. In that case, the grid columns are dynamically generated from the fields of the dataset. The order of columns in the grid matches the order of fields in the dataset, and the display of data is determined by the properties of the fields in the dataset.
The dynamic field components are destroyed each time the dataset is closed. All dynamic columns are destroyed as well. On the other hand, if the dataset has persistent field components, they exist even when the dataset is closed: the columns associated with those fields retain their properties when the dataset is closed.
Persistent column objects are set up at design time, i.e. with Delphi's Column Editor.
To create persistent columns, select the grid component in the form and next double click on the Columns property in the Object Inspector. Shortcut: you can also double-click on the grid.
When you first bring up the Columns editor, it shows an empty list. You can create persistent columns for all fields in a dataset at once with the button Add All Fields, or you can create persistent columns on an individual basis:
Deleting a persistent column from a grid is useful for eliminating fields that you do not want to display. To remove a persistent column, double-click the grid to display the Columns editor. Next, select the field to remove in the listbox. Next, click the button Delete (or press the Del key on your keyboard.
If you delete all the columns from a grid, Delphi automatically builds dynamic columns for each field in the dataset.
- Click the Add button in the Columns editor. A new column will appear the list box. The new column is given a sequential number and default name, for example: 0 and "TColumn".
- Associate a field with this new column: set the FieldName property in the Object Inspector.
Important! If Delphi doesn't know the location of the dataset, you get the error message "Missing data provider or data packet".
- If you are using a ClientDataSet, select the dataset component and in the Object Inspector set its property FileName to an existing file on the disk.
- If you are using another kind of dataset component, in the Object Inspector set its properties that are necessary to identify the source of the data. For example, for a "FireDAC" application, set the DriverID and the Database file of the FDConnection component. And so on.
- To set the title for the new column, expand the Title property in the Object Inspector. You can set its properties Caption, Alignment, Color and Font.
- Close the Columns editor to apply the persistent columns to the grid.
Defining the appearance at runtime
You can specify some Column properties in code:
- FieldName: the name of the field represented by the column.
- Alignment: specifies how text is aligned within the column: left-justified, right-justified, or centered.
- Color: the background color for the column.
- Font: font in which the column displays its data. Points to a TFont object that determines typographic attributes of text displayed in the column.
- Title: holds information about a column's title. See below for more details.
- Visible: specifies whether the column is visible in the grid. To hide a column in the grid, set Visible to false.
- Width: width of the column in pixels. Default value: 64.
Each Column object has a ColumnTitle object that holds information about its title; properties are:
You can delete a persistent column at run time by "freeing" the column object, for example:
- Alignment: specifies how text is aligned within the column title: left-justified, right-justified, or centered.
- Caption: the text that appears at the top of the column. If you don't specify this, by default the FieldName of the column is used.
- Color: the background color for the column title. You can set Color to one of the constants defined in Delphi (such as clBlue), or to an explicit RGB integer value. The default value is the grid's FixedColor property. Note: this only functional if the DrawingStyle of the grid is set to gdsClassic.
- Font: the font in which the column title displays its caption. It points to a TFont object that determines typographic attributes of text displayed in the column title. The default value is the grid's TitleFont property.
DBGrid1.DrawingStyle := gdsClassic; // for Title.Color
DBGrid1.Columns.FieldName := 'Name';
DBGrid1.Columns.Width := 120;
DBGrid1.Columns.Title.Alignment := taCenter;
DBGrid1.Columns.Title.Caption := 'Last Name';
DBGrid1.Columns.Title.Color := clAqua;
// DBGrid1.Columns... and so on
Color of grid cells
If you want to display some dbgrid cells in a different color, depending on the contents of the associated field, you write code for the OnDrawColumnCell of the grid. Example:
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
if Column.FieldName = 'Temperature' then
if CDS.FieldByName('Temperature').AsFloat < 0 then begin
DBGrid1.Canvas.Font.Color := clWhite; // the text
DBGrid1.Canvas.Brush.Color := clRed; // the background
DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State);
Other Grid Options
You can use the grid Options property at design time to control basic grid behavior and appearance. In the Object Inspector, click on the + (plus) sign to expanded to display a series of Boolean properties that you can set individually. Here are some of the options:
- dgEditing: the user can edit, insert, and delete records in the grid. Ignored if Options includes dgRowSelect. Default: True.
- dgAlwaysShowEditor: the grid is always in edit mode. The user does not have to press ENTER or F2 before editing the contents of a cell. Does nothing unless dgEditing is also included in Options. Is ignored if Options includes dgRowSelect. Default: False.
- dgTitles: titles appear at the top of the columns. Default: True.
- dgIndicator: the current record indicator is displayed at the left of the grid. When you just browse the table, the current record indicator is an arrow; when you insert a record, the indicator is an asterisk; when you edit a record, the indicator is an I-beam. Default: True.
- dgColumnResize: the user can resize the width of the columns by dragging the column rulers in the title area, and can move the columns. Default: True.
- dgColLines: displays vertical lines between columns. Default: True.
- dgRowLines: displays horizontal lines between rows. Default: True.
- dgTabs: the user can navigate through the grid using the TAB and SHIFT+TAB keys. Default: True.
- dgRowSelect: an entire row is selected instead of an individual cell. If Options includes dgRowSelect, both dgEditing and dgAlwaysShowEditor are ignored. Default: False.
- dgAlwaysShowSelection: the selected cell displays the focus rectangle, even when the grid does not have focus. Default: True.
- dgConfirmDelete: a message box asks for confirmation, when the user presses Ctrl+Delete to delete a row. Default: True.
- dgCancelOnExit: when the user exits the grid from an inserted record to which no modifications were made, the inserted record is not posted to the dataset. This prevents the inadvertent posting of empty records. Default: True.
- dgMultiselect: the user can select multiple rows, by pressing the Ctrl key and clicking with the mouse. Default: False.
Multiple row selection
You can set up the DBGrid so that a user can select multiple rows (multiple records). Set the dgMultiSelect element of the grid's Options property to True. Now a user can keep the Ctrl key pressed and click with the mouse to select multiple grid rows.
The grid keeps a list of bookmarks to the selected records. This list is available in the SelectedRows property. You can get to each bookmark. Let's look at an example to illustrate this.
Suppose that you have a database that includes a field "Amount". You want to display the total amount for the records that the user has selected. The code can be:
procedure TForm1.Button1Click(Sender: TObject);
i, Total: integer;
Bookmark := cds.Bookmark; // save current position
BookmarkList := DbGrid1.SelectedRows; // get bookmarks of selected rows
if BookmarkList.Count = 0 then
ShowMessage('No records were selected')
Total := 0;
for i := 0 to BookmarkList.Count - 1 do begin
// for each selected row, move table to that record
cds.Bookmark := BookmarkList[i];
// add Amount to Total
Total := Total + CDS.FieldByName('Amount').AsInteger;
CDS.Bookmark := Bookmark; // return to saved position
ShowMessage('Total selected Rain: ' + IntToStr(Total));