DBGridであるセルに色を付ける
StringGridなどには独自描画処理のために OnDrawCellイベントが用意されていますが、 DBGridにはありません。その代わりOnDrawColumnCellイベントを使います。
DBGrid の DefaultDrawingプロパティを Falseに設定して OnDrawColumnCellイベントに
Canvasへの描画処理を記述します。
Rect引数には描画対象となる領域、DataCol引数には描画対象の列インデックス、Column引数にはグリッドの列、State引数にはセルの状態が渡されます。
※OnDrawDataCellイベントも用意されていますが、こちらは下位互換を保つためだけにあります。ですので使用しないで下さい。
| ■ DBGridのセルに色を付ける例 |
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
with DBGrid1.Canvas do begin
if not (gdSelected in State) then begin //選択セルなら処理無し
//3列目は青に。
if DataCol = 2 then begin
Font.Color := clYellow;
Brush.Color := clBlue;
FillRect(Rect);
end;
//"SIZE"フィールドが2の場合はその行を赤に。
if DBGrid1.DataSource.Dataset.FieldByName('SIZE').AsInteger = 2 then begin
Brush.Color := clRed;
Font.Color := clWhite;
FillRect(Rect);
end;
end;
//描画処理を実行
DBGrid1.DefaultDrawColumnCell(Rect,DataCol,Column,State);
end;
|