Coloring DBGrid
Adding color to your database grids will enhance the appearance and differentiate the importance of certain rows or columns within the database.
Since the DBGrid is a great user interface tool for displaying data, this article will focus on questions like “How do I change the color of particular row / column / cell in a DBGrid?”
Preparations
Select the employee.db from DBDemos alias. Select all fields except EmpNo.
Coloring Columns
The first (and the easiest) thing you can do, to visually enhance the user interface, is to color individual column in the data-aware grid.
We will accomplish this through TColumns property of the grid. Select the grid component in the form and invoke the Columns editor by double clicking on the grid’s Columns property in the Object Inspector. For more information on Columns editor look for “Columns editor: creating persistent columns” in your Delphi help files.
Now, everything you have to do is to specify the background color of the cells of the particular column. For text foreground color, see the font property.
If you want to color the selected row in a DBGrid but you don’t want to use the dgRowSelect option because you want to be able to edit the data you should use the DBGrid.OnDrawColumnCell event.
This technique demonstrates how to dynamically change the color of text in a DBGrid:
1 2 3 4 5 6 7 8 9 10 |
procedure TForm1.DBGrid1DrawColumnCell (Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if Table1.FieldByName('Salary').AsCurrency>36000 then DBGrid1.Canvas.Font.Color:=clMaroon; DBGrid1.DefaultDrawColumnCell (Rect, DataCol, Column, State); end; |
If an employee’s salary is greater than 36 thousand, its row is displayed in Maroon colored text. Next technique demonstrates how to dynamically change the color of row in a DBGrid:
1 2 3 4 5 6 7 8 9 10 |
procedure TForm1.DBGrid1DrawColumnCell (Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if Table1.FieldByName('Salary').AsCurrency>36000 then DBGrid1.Canvas.Brush.Color:=clWhite; DBGrid1.DefaultDrawColumnCell (Rect, DataCol, Column, State); end; |
Coloring Cells
And finally: if you want to change the background color of the cells of the particular column (+ text foreground color), this is what you have to do:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
procedure TForm1.DBGrid1DrawColumnCell (Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if Table1.FieldByName('Salary').AsCurrency>40000 then begin DBGrid1.Canvas.Font.Color:=clWhite; DBGrid1.Canvas.Brush.Color:=clBlack; end; if DataCol = 4 then //4 th column is 'Salary' DBGrid1.DefaultDrawColumnCell (Rect, DataCol, Column, State); end; |