DBGrid-如何设置单独的背景色? [英] DBGrid - How to set an individual background color?

查看:54
本文介绍了DBGrid-如何设置单独的背景色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Delphi 10.2.3,并且想要更改DBgrid的背景颜色.例如,我有一个文本列和一个整数列.如果值不为零,我想根据文本更改整数单元格(在同一行中)的颜色.

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.

我从中得到了一些想法如何为DBGrid特殊单元着色?所以我知道如何在OnDrawColumnCell中更改单元格的颜色.我可以更改文本的背景.但是我仍然不知道如何更改另一个单元格的颜色.当然,这很容易,而且我对明显的事物视而不见.

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.

推荐答案

以下代码显示了如何根据值位于同一网格行的另一列中.

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;

这篇关于DBGrid-如何设置单独的背景色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆