最简单的方法可能是使用表单的OnCreate
填充数组,然后访问OnGetCellParams
事件中的数据。该数组应该包含尽可能多的项目,因为有可能的值,加上数组索引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
事件:
Background := FColors[DBGrid.Field.AsInteger];
您可能需要使用局部变量在OnGetCellParams
以确保您留在阵中范围:
Background := clWindow;
i := DBGrid.Field.AsInteger;
if (i > 0) and (i < Length(FColors)) then
Background := FColors[i];
慢得多的方法是做一个Locate
在OnGetCellParams
事件每一行:
在OnGetCellParams
:
Background := clWindow;
if dmAppData.FieldColors.Locate('ColValue', DBGrid.Field.AsInteger, []) then
Background := TColor(dmAppData.FieldColors.FieldByName('Color').AsInteger);
谢谢 因为我的表将保存的数据非常有限(小)量,我想我会用“定位”选项去。有趣的是,它在运行时提示“多步操作生成错误”。我一定会尝试'数组'的方法。 – SilverCrest 2012-07-19 04:03:08