I have noticed on Polish discussion forums devoted to Delphi programming
(such as news://pl.comp.lang.delphi
and news://pl.comp.lang.delphi.bazy-danych) there are often questions
about changing colors in DBGrid. It is a very easy task and I would like
to offer some clues here.
The first step is to turn off the DefaultDrawing
property of DBGrid by setting its value to False.
Let's consider the following example:
-
We have a dataset which is using CachedUpdates.
-
The user wants to know which records were edited, which are new, and which
were deleted.
Such information about CachedUpdates can be accessed with the UpdateStatus
function. To display records deleted from the dataset (before applying
updates) we will modify the UpdateRecordTypes property. This property
specifies which records should be visible in a dataset -- by default it is equal
to [rtModified, rtInserted, rtUnmodified]. So
in our code we must add a following line:
UpdateRecordTypes := UpdateRecordTypes + [rtDeleted];
Now let's go to DBGrid and add a handler for the OnDrawColumnCell event as follows:
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
with (Sender as TDBGrid).Canvas do begin
case (DataSource.DataSet as TBDEDataSet).UpdateStatus of
usInserted : Brush.Color := clRed;
usModified : Brush.Color := clBlue;
usDeleted : begin Brush.Color := clBlack; Font.Color := clWhite; end;
end;
DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
end;
DefaultDrawDataCell will now draw text using new font and brush properties. Easy, isn't it?