如何为DBGrid特殊单元着色? [英] how to color DBGrid special cell?

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

问题描述

我有一列只有 yes和 no值。
我想要的是,如果列值是 yes,那么只有该单元格的背景色是红色的
否则是 no,那么背景色是黄色的
,但是此代码将整个行着色:

I have a column which have only "yes" and "no" values. I want if column value is "yes" then only that cell background color is red else "no" then background color is yellow but this code colors whole row :

if ADOTable1.FieldByName('Clubs').AsString = 'yes' then
begin
  DBGrid1.Canvas.Brush.Color := clRed;
  DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;

编辑

感谢您的答复。
我的真实代码如下所示。 netice列仅包含 L,D,W。

Thanks for your replies. My real code look like that. The "netice" column only have "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;

但我需要L-绿色,D-红色,W-黄色
我正在使用Delphi 2010。

but I need L--green, D--red, W--yellow I am using Delphi 2010.

推荐答案

您需要添加条件以将笔刷颜色的更改限制到您选择的列。在代码中可能是:

You need to add a condition to restrict changing of the brush color only to 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's column assigned field reference
  // (if any) to the local variable (there's quite expensive getter)
  Field := Column.Field;
  // if the rendered cell's 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;

我希望在 Column.FieldName ,因为 Column.FieldName 尚不能保证链接数据集中有该字段。因此,以这种方式直接访问字段更安全。

I'd prefer this before Column.FieldName because Column.FieldName does not yet guarantee that there is such field in the linked dataset. Accessing the field directly is therefore safer in this manner.

这篇关于如何为DBGrid特殊单元着色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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