«« Site Rescued »»

While the site is still going to move from its current host, a new site will now take its place. More Info.

The new site may have less content, but the core will now remain. And it will now play nicely with phones! Keep an eye on the DelphiDabbler Blog for news.

» Help

Draw a DBGrid with alternating row colours


You've seen this surely on web pages. Alternating table row colors means displaying the first record in one color and the second record in another color and continue to alternate the color of each row displayed.

When working with datasets with many rows, alternating the background color of each row can increase readability.

Here's the OnDrawColumnCell event handler for a DBGrid control to color every second row in a different color.

procedure TGridForm.DBGridDrawColumnCell(Sender: TObject; const Rect: TRect;
  DataCol: Integer; Column: TColumn; State: TGridDrawState);
  grid : TDBGrid;
  row : integer;
  grid := sender as TDBGrid;
  row := grid.DataSource.DataSet.RecNo;
  if Odd(row) then
    grid.Canvas.Brush.Color := clSilver
    grid.Canvas.Brush.Color := clDkGray;
  grid.DefaultDrawColumnCell(Rect, DataCol, Column, State) ;
end; (* DBGrid OnDrawColumnCell *)

Note that the row color eliminates the need of table borders and make it easy for the eye to read a row. In a vertical sense, the colors make it easier to 'catch' an item because it is on either one of the colors.

Of course, you need to take into consideration the color of the selected cell/row - I'll leave this up to you - but this should help:

Play with the Options property to have the best looking grid for your Delphi application :)

Author: Unknown
Contributor: Riccardo Faiella (Topellina)
Added: 2012-07-06
Last updated: 2012-07-06

« Return to contents »