Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

dbgrid row color solution 2

Status
Not open for further replies.

DelphiAaron

Programmer
Jul 4, 2002
826
AU
i found code to color odd and even rows of a dbgrid, but the code relies on the dataset record number to get its odd and even.

the problem is that if you set a filter on the dataset to show only odd or even records then the grid wont apply the different colors to the rows.

anyone know a way round ?

Aaron Taylor
John Mutch Electronics
 
This is quite easy to do although the solution might not be obvious as the row number that is being drawn is not readily available.

However, if you just want alternate colour bands on your grid then this works.

Set DefaultDrawing to false. Code a DrawColumnCell event handler. In the handler divide the value of Rect.Top by the height of each row and if the answer is odd then use one colour otherwise use the other colour. I've hard coded the height (18) of the each row in the grid to make the coding more readable.

Code:
procedure TForm1.gridDrawColumnCell(Sender: TObject; const Rect: TRect;
  DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
  if Odd(rect.top div 18) then
    grid.canvas.brush.color := clAqua
  else
    grid.Canvas.brush.color := clWhite;
  grid.canvas.TextRect(rect,rect.Left,rect.top,table.fields[DataCol].AsString);
end;

Andrew
Hampshire, UK
 
works ok when the grid loads
but the colors screw up when you scroll.

im using a third party grid that has a dedicated procedure or method for coloring rows the only problem is getting the odd and even rows based on the grid records not the table record number.

Aaron Taylor
John Mutch Electronics
 
Try adding an AfterScroll event to the dataset. Something like this works for me but I've only tested it with the standard Delphi 7 components TDBGrid and TTable.
Code:
procedure TForm1.TableAfterScroll(DataSet: TDataSet);
begin
  grid.Invalidate;
end;

Andrew
Hampshire, UK
 
I assume that you mean 'selected row' by 'highlighted row'.

What have you tried so far?

Tek-Tips is not a free programming service, you know!

Andrew
Hampshire, UK
 
this works for me when placed at the end of the DBGrid1DrawColumnCell event don't know if might help you

if (gdSelected in State) then
begin
DBGrid1.Canvas.Font.Color := clWhite;
DBGrid1.Canvas.Brush.Color := clHighlight;;
DBGrid1.Canvas.FillRect(Rect);
DBGrid1.Canvas.TextOut(Rect.Left, Rect.Top,Column.Field.DisplayText);
end;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top