Re: Stringgrid cell colour: yellow on red if negative?

Posted by Jenny, DelphiLand Team on July 20, 2008

In Reply to Stringgrid cell colour: yellow on red if negative? posted by Harry D. P16510 on July 18, 2008

: How would I code it if I also want a different background in the cells? For example, yellow text on a red background for negative values?

: How to limit this to certain columns and rows, for example only in the second column, without colouring the top row (top row used as fixed row for titles)?

In order to limit the cell colouring, you expand the IF condition with "exclude the top row" and "only if the column is the second column":

if (ARow > 0) and (ACol = 1) and
   (Length(S) > 0) and (S[1] = '-') then begin

For the colouring of the cell:
- Firstly, set the StringGrid.Canvas.Brush colour to the desired cell background colour, for example: clRed.
- Next, fill the cell rectangle with that colour.
- Next, set the StringGrid.Canvas.Font.Colour to the desired cell foreground colour, for example: clYellow.
- Finally, output the text of the cell.

Delphi source code example:

procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
  Rect: TRect; State: TGridDrawState);
var
  S: string; // string displayed in the cell
begin
  S := StringGrid1.Cells[ACol, ARow]; // cell contents
  // If row is not the fixed row and...
  // column is the second column and...
  // first character of cell contents is a minus sign
  if (ARow > 0) and (ACol = 1) and
     (Length(S) > 0) and (S[1] = '-') then begin
    // Fill rectangle with red
    StringGrid1.Canvas.Brush.Color := clRed;
    StringGrid1.Canvas.FillRect(Rect);
    // Show cell contents in yellow
    StringGrid1.Canvas.Font.Color  := clYellow;
    StringGrid1.Canvas.TextOut(Rect.Left + 2, Rect.Top + 2, S);
  end;
end;
 

Related articles

       

Follow Ups