The code below shows how to change the background colour of a cell depending on the
value in another column in the same grid row.
procedure TForm1.FormCreate(Sender: TObject);
var
AField : TField;
begin
AField := TIntegerField.Create(Self);
AField.FieldKind := fkData;
AField.FieldName := 'ID';
AField.DataSet := ClientDataSet1;
AField := TStringField.Create(Self);
AField.FieldKind := fkData; // Field size defaults to 20
AField.FieldName := 'AValue';
AField.DataSet := ClientDataSet1;
ClientDataSet1.CreateDataSet;
ClientDataSet1.InsertRecord([1, 'One']);
ClientDataSet1.InsertRecord([2, 'Two']);
ClientDataSet1.InsertRecord([3, 'Three']);
DBGrid1.DefaultDrawing := False; // otherwise DBGrid1DrawColumnCell will have no effect
end;
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
if Column.Index = 1 then begin
if Odd(DBGrid1.Columns[0].Field.AsInteger) then
DBGrid1.Canvas.Brush.Color := clGreen;
end;
DBGrid1.DefaultDrawDataCell(Rect, Column.Field, State);
end;
If you wanted to determine the cell colour depending on the value of an undisplayed
field (one that has no grid column) you could simply test the value of the field
in the underlying dataset, because the logical dataset cursor is always synchronized
with the cell currently being drawn. E.g.
if Odd(DBGrid1.DataSource.DataSet.Fields[99].AsInteger) then
DBGrid1.Canvas.Brush.Color := clGreen;