Uses OnBeforeDrawCell
to change the look of some cells according to their data, and to fill a
column that has no field with a value computed from the other fields of
its row.
Price * Quantity, formatted as money.In the Columns editor add the columns Name,
Price, Quantity, Stock, and one
more column with no FieldName, titled
Total, with Alignment =
Trailing. Give the grid an image list with a warning icon
at index 0.
Besides EgFireGrid, the handler uses
System.SysUtils (SameText,
FormatFloat), System.Variants
(VarIsNull) and System.UITypes
(TAlphaColors, TFontStyle).
procedure TForm1.Grid1BeforeDrawCell(Sender: TObject; Column: TEgFireGridColumn; RowIndex: Integer;
Cell: TEgFireGridCellControl; var Text: string);
var
Price, Quantity, Stock: Variant;
begin
if SameText(Column.FieldName, 'Price') then
begin
Price := Grid1.RowSource.GetValue(RowIndex, 'Price');
if not VarIsNull(Price) and (Price < 0) then
begin
Cell.BackColor := $FFFFE0E0;
Cell.CellFontColor := TAlphaColors.Red;
Cell.CellFontStyle := [TFontStyle.fsBold];
end;
end
else if SameText(Column.FieldName, 'Stock') then
begin
Stock := Grid1.RowSource.GetValue(RowIndex, 'Stock');
if not VarIsNull(Stock) and (Stock <= 0) then
Cell.ImageIndex := 0;
end
else if SameText(Column.Title.Caption, 'Total') then
begin
Price := Grid1.RowSource.GetValue(RowIndex, 'Price');
Quantity := Grid1.RowSource.GetValue(RowIndex, 'Quantity');
if VarIsNull(Price) or VarIsNull(Quantity) then
Text := ''
else
Text := FormatFloat('#,##0.00', Price * Quantity);
end;
end;
RowSource.GetValue(RowIndex, ...): the dataset’s current
record is not moved to the row being drawn, so
Query1.FieldByName(...) would read the active record
instead.Columns).CellFontColor and CellFontStyle; the cell’s
own Font and FontColor are set by the grid
after the event.The same code can be split over the columns’ own
OnBeforeDrawCell events, one handler per column, which
removes the tests on Column. See OnBeforeDrawCell.