DBGrid - How to set an individual background color?

时间秒杀一切 提交于 2021-02-09 09:23:47

问题


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:


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;


来源:https://stackoverflow.com/questions/57267946/dbgrid-how-to-set-an-individual-background-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!