1

Delphi XE-2 と Jedi コンポーネント グループ (TJvDBGrid) の DBGrid を使用しています。ここで、値がわかっている場合、セルの色を定義するのは非常に簡単であることがわかりました。たとえば、次のようになります。

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

しかし、私の場合、ユーザーはどの値がどの色を持つかを定義でき、それは別のテーブルに保存されます。そして私の質問は、セル値に色が割り当てられているかどうかを調べてセルに色を付ける方法はありますか?

この件についてご助言やご指導をいただければ幸いです。ありがとうございます。

4

1 に答える 1

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];

はるかに遅い方法は、すべての行に対してイベントでLocateを実行することです。OnGetCellParams

OnGetCellParams

Background := clWindow;
if dmAppData.FieldColors.Locate('ColValue', DBGrid.Field.AsInteger, []) then
  Background := TColor(dmAppData.FieldColors.FieldByName('Color').AsInteger);
于 2012-07-18T21:53:23.757 に答える