3
votes

I am using Delphi 10.2.3 and want to change the background color of a DBgrid. For example I have a text column and an integer column. Depending on the text I want to change the color of the integer cell (in the same row) if the value is non-zero.

I got some ideas from how to color DBGrid special cell? So I know how to change the color of a cell in OnDrawColumnCell. I can change the background of the text. But I still didn't figure out how to change the color of another cell. Certainly it is pretty easy and I am only too blind to the the obvious.

1

1 Answers

5
votes

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;