Search code examples
delphifiremonkeytstringgrid

TStringgrid change color of row conditionally in firemonkey


How to paint an entire row based on some value in a particular column? I have TStringGrid with four columns:

 ID  | NAME   |   DATE      |  STATE
 1     X       2017-01-01      TRUE          --whole row need to be yellow
 2     Y       2017-01-01      FALSE         --default color (no change) 

If my column state has value true repaint whole row to be yellow.

I have tried this but it only works on column state:

procedure TTNarudzbenice.grSomeNameDrawColumnCell(Sender: TObject; const Canvas: TCanvas; const Column: TColumn; const Bounds: TRectF;const Row:Integer; const Value: TValue; const State: TGridDrawStates);
var
  aRowColor: TBrush;
begin

  aRowColor := Tbrush.Create(TBrushKind.Solid,TAlphaColors.Alpha);
  //-----
   if Value.ToString = 'TRUE' then
    begin
    aRowColor.Color := TAlphaColors.Yellow;

    Canvas.FillRect(Bounds, 0, 0, [], 1, aRowColor);

    Column.DefaultDrawCell(Canvas, Bounds, Row, Value, State);

end;

    aRowColor.free;

end;

Solution

  • Just a simple adjustment

    procedure TTNarudzbenice.grSomeNameDrawColumnCell(Sender: TObject; const Canvas: TCanvas; const Column: TColumn; const Bounds: TRectF;const Row:Integer; const Value: TValue; const State: TGridDrawStates);
    var
      aRowColor: TBrush;
    begin
    
      aRowColor := Tbrush.Create(TBrushKind.Solid,TAlphaColors.Alpha);
      //-----
      if (Sender as TStringGrid).Cells[ 3, Row ] = 'TRUE' then  //// This line changed
      begin
        aRowColor.Color := TAlphaColors.Yellow;
    
        Canvas.FillRect(Bounds, 0, 0, [], 1, aRowColor);
    
        Column.DefaultDrawCell(Canvas, Bounds, Row, Value, State);
    
      end;
      aRowColor.free;
    
    end;
    

    The better to use a const value instead of '3' in case the column changes. The point is that this routine will be called for all cells, but you only ever want to compare the value of the 4th column, regardless of which cell is being currently drawn