Link to home
Create AccountLog in
Avatar of ginsonic
ginsonicFlag for Romania

asked on

DBGrid & row color

I have a field with nexts possible values : 'o' , '' or 'n'. I wish that in my DBGrid to show with green rows all lines what have 'o' value assigned, red for 'n' and white for ''.

Attention, I wish all ROW colored and NOT only CELL where is displayed 'o' or 'n'.
Avatar of shaneholmes

    { Set default font color }
    DBGrid1.Canvas.Font.Color := clBlack;
    { Is current cell the focused cell? }
    if (gdFocused in State) then begin
      DBGrid1.Canvas.Brush.Color := clBlack;
      DBGrid1.Canvas.Font.Color := clWhite;
    { Not focused, is it the target field Terms? }
    else if (Field.FieldName = MYFIELDNAMEHERE) then
      { Check field content for one of two possible values }
      if (Field.AsString = 'o') then
        { If field contains "o" paint  green}
        DBGrid1.Canvas.Brush.Color := clGreen
        { If field contains "n" paint red }
        DBGrid1.Canvas.Brush.Color := clPaleRed
      { Paint non-focused and non-target cells white }
      DBGrid1.Canvas.Brush.Color := clWhite;
       DBGrid1.DefaultDrawDataCell(Rect, Field, State);

Oops, the code should be place in the TDBGrids OnDrawDataCell event

see the entir article here:,1410,20845,00.html

Avatar of Ferruccio Accalai
Ferruccio Accalai
Flag of Italy image

Link to home
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of ginsonic


Attention, I wish all ROW colored and NOT only CELL where is displayed 'o' or 'n'.

Your code change the color just for cell. This can be done more easier in DrawColumn.
The message was for shaneholmes :)
sorry, i extrapolated from the link i provided, and didn't change everything that was appropriate to your question

it could have easily been changed to test the fieldbyname versus each individual field

if (DBGrid1.FieldByName = MYFIELDNAMEHERE) = '0' then
        DBGrid1.Canvas.Brush.Color := clGreen
if (DBGrid1.FieldByName = MYFIELDNAMEHERE) = '1' then
          DBGrid1.Canvas.Brush.Color := clPaleRed

Oh well, you win some, you loose some

Still color just a cell.

I have a new problem. In my project I have a DBGrid with specified columns. When I test these comments I used a demo project where I show all fields. In this case all work perfect.

But when I ported the demo code to my app don't work. Look alike DrawCell isn't called when I declare some columns. Some help here? New 250 points available.
Found already a way in DrawColumn event. Thanks for support!