2012-07-18 86 views
1

我使用Jedi組件組(TJvDBGrid)中的Delphi XE-2和DBGrid。現在,我發現它是非常容易定義單元格顏色當值已知,例如:動態DBGrid單元格着色

OnGetCellParams event: 
if DBGrid.Field.AsInteger = 0 
then Background := clYellow; 

,但在我的情況下,用戶可以定義什麼值會產生什麼樣的顏色,存儲在單獨的表。而我的問題是,有沒有一種方法通過查找顏色單元格的顏色是否賦予顏色?

我很感謝您對此事的任何幫助或指導,謝謝。

回答

2

最簡單的方法可能是使用表單的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]; 

慢得多的方法是做一個LocateOnGetCellParams事件每一行:

OnGetCellParams

Background := clWindow; 
if dmAppData.FieldColors.Locate('ColValue', DBGrid.Field.AsInteger, []) then 
    Background := TColor(dmAppData.FieldColors.FieldByName('Color').AsInteger); 
+0

謝謝 因爲我的表將保存的數據非常有限(小)量,我想我會用「定位」選項去。有趣的是,它在運行時提示「多步操作生成錯誤」。我一定會嘗試'數組'的方法。 – SilverCrest 2012-07-19 04:03:08