delphiscrollcellfiremonkeytgrid

Firemonkey XE5 TGrid scrolling issue using formatted cells


I'm using Delphi XE5 and am trying to format a TGrid based on the contents of each cell. For numerics I'd like them right-aligned in the cell with negatives shown in red font. All other data should be left-aligned in the cell. The following code achieves this EXCEPT when I scroll the grid up or down the colour/alignment goes wrong.

type
  TMyColumn = class( TStringColumn )
end;

procedure TForm1.Grid1GetValue(Sender: TObject; const Col, Row: Integer;
  var Value: TValue);
var
  vMyCell : TStyledControl;
  i : Integer;
  s : String;
begin

  s := gHoldingGrid.Cells[ Col, Row ];

  vMyCell := TMyColumn( Grid1.Columns[ Col ] ).CellControlByRow( Row );

  if ( ( vMyCell <> nil ) AND ( vMyCell is TTextCell ) )
  then begin
    TTextCell( vMyCell ).StyledSettings := [];

    if TryStrToInt( s, i )
    then begin
      if StrToInt( s ) < 0
      then TTextCell( vMyCell ).FontColor := claRed
      else TTextCell( vMyCell ).FontColor := claBlue;

      TTextCell( vMyCell ).TextAlign := TTextAlign.taTrailing;
    end  { if TryStrToInt( s, i ) }
    else begin
      TTextCell( vMyCell ).TextAlign := TTextAlign.taLeading;
      TTextCell( vMyCell ).FontColor := claGreen;
    end;  { else .... if TryStrToInt( s, i ) }

    vMyCell.ApplyStyleLookup;
  end;  { if ( ( vMyCell <> nil ) AND ( vMyCell is TTextCell ) ) }

  Value := s;

end;

Can someone help me solve this please? I've tried numerous examples on this forum but couldn't get them working and am well and truly stuck.

Many thanks in anticipation.


Solution

  • When a FireMonkey grid is scrolled the cells become recycled. New values are passed into the cells via the SetData method. Therefore you need a custom component for use as a cell which overrides SetData to apply the formatting.

    Thus you need to subclass TTextCell (which itself simply subclasses TEdit) and you also need a new column class which will create cells of your new class.

    This is all much simpler than it sounds when you understand it. I have an article with an example at http://monkeystyler.com/guide/Formatting-a-Column-as-Currency and there are other articles linked from there which will be of use to you.