首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >动态DBGrid单元格着色

动态DBGrid单元格着色
EN

Stack Overflow用户
提问于 2012-07-19 04:52:54
回答 1查看 1.6K关注 0票数 1

我使用的是绝地组件组(TJvDBGrid)的Delphi 2和DBGrid。现在,我发现当值已知时,定义单元格颜色非常容易,例如:

代码语言:javascript
代码运行次数:0
运行
复制
OnGetCellParams event: 
if DBGrid.Field.AsInteger = 0
then Background := clYellow;

但在我的例子中,用户可以定义什么值将具有什么颜色,存储在单独的表中。我的问题是,有没有一种方法可以通过查找单元格值是否有指定的颜色来给单元格着色?

感谢您在这件事上的任何帮助或指导,谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-07-19 05:53:24

最简单的方法可能是使用表单的OnCreate填充一个数组,然后在OnGetCellParams事件中访问该数组。数组应该包含尽可能多的项,如果没有指定颜色,则数组索引为0。(下面是未经测试的即兴代码!)

代码语言:javascript
代码运行次数:0
运行
复制
type
  TForm1 = class(TForm)
    ...
    procedure FormCreate(Sender: TObject);
  private
    FColors: array of TColor;
  end;

implementation

procedure TForm1.FormCreate(Sender: TObject);
var
  NumRows, i: Integer;
begin
  // One row for each possible value for the integer column you're
  // trying to color the cell for (eg., if the table can hold a value
  // from 0-10, you need the same # of items in the array (array[0..10])
  NumRows := NumberOfPossibleValues;
  SetLength(FColors, NumberOfPossibleValues);

  // Pre-fill the array with the default clWindow color,
  // in case a custom color isn't assigned to a value
  // (for instance, the user doesn't set a color for a value
  // of 7).
  for i := 0 to High(FColors) do
    FColors[i] := clWindow;  

  // Assumes your color values are in a database called FieldColors,
  // in a datamodule called dmAppData, and that there's a
  // column named ColValue indicating the `Field.AsInteger`
  // value and the corresponding TColor stored as an integer.
  dmAppData.FieldColors.First;
  while not dmAppData.FieldColors.Eof do
  begin
    i := dmAppData.FieldColors.FieldByName('ColValue').AsInteger;

    // Might want to put a check here to make sure the value isn't
    // more than the number of items in the array!!!
    FColors[i] := TColor(dmAppData.FieldColors.FieldByName('Color').AsInteger);
    dmAppData.FieldColors.Next;
  end;
end;

在您的OnGetCellParams事件中:

代码语言:javascript
代码运行次数:0
运行
复制
Background := FColors[DBGrid.Field.AsInteger];

您可能希望在OnGetCellParams中使用局部变量,以确保保持在数组边界内:

代码语言:javascript
代码运行次数:0
运行
复制
Background := clWindow;
i := DBGrid.Field.AsInteger;
if (i > 0) and (i < Length(FColors)) then
  Background := FColors[i];

更慢的方法是在OnGetCellParams事件中为每一行执行一个Locate

OnGetCellParams

代码语言:javascript
代码运行次数:0
运行
复制
Background := clWindow;
if dmAppData.FieldColors.Locate('ColValue', DBGrid.Field.AsInteger, []) then
  Background := TColor(dmAppData.FieldColors.FieldByName('Color').AsInteger);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11550160

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档