How to color a custom DBGrid cell?
I have a column that only has yes and no values. I want the column value to be "yes" then only the background color of the cell otherwise "no" then the background color is yellow but this code colors the whole row:
if ADOTable1.FieldByName('Clubs').AsString = 'yes' then
begin
DBGrid1.Canvas.Brush.Color := clRed;
DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
EDIT
Thank you for your responses. My real code looks like this. The "netice" column only has "L, D, W".
if Column.FieldName = 'netice' then
begin
if ADOTable1.FieldByName('netice').AsString = 'L' then
DBGrid1.Canvas.Brush.Color := clgreen ;
if ADOTable1.FieldByName('netice').AsString = 'D' then
DBGrid1.Canvas.Brush.Color := clRed ;
if ADOTable1.FieldByName('netice').AsString = 'W' then
DBGrid1.Canvas.Brush.Color := clYellow ;
end;
DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
but I need L for green, D for red, W for yellow I am using Delphi 2010.
source to share
You need to add a condition to restrict the brush color change to only the column of your choice. In code, it could be:
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
Field: TField;
begin
// store the currently rendered cell column assigned field reference
// (if any) to the local variable (there quite expensive getter)
Field := Column.Field;
// if the rendered cell column has assigned a field and this field's
// name is 'Clubs' (compared without case sensitivity), then, and only
// then change the brush color...
if Assigned(Field) and SameText(Field.FieldName, 'Clubs') then
begin
if Field.AsString = 'yes' then
DBGrid1.Canvas.Brush.Color := clRed
else
DBGrid1.Canvas.Brush.Color := clYellow;
end;
DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
I would have preferred this before Column.FieldName
because it Column.FieldName
does not yet guarantee that there is such a field in the associated dataset. Thus, accessing the field directly is safer.
source to share