Posted by Jenny, DelphiLand Team on July 17, 2008
In Reply to stringgrid cell colour: red if negative posted by Harry D. P16510 on
July 15, 2008
: How to colour a stringgrid cell in red, if that cell contains a negative value?
: For 0 or positive numbers, it should keep the original colours, such as black text on white background.
Each time a cell is drawn, a Delphi TStringGrid component raises an OnDrawCell event. If you want to change the default cell-drawing, you have to write an event handler for OnDrawCell.
Say that you want negative numbers in red on white. For this example, let's assume a stringgrid with the name "Grid", and that all its cells contain strings that represent valid numbers.
1. On your form, click the component "Grid".
2. In the Object Inspector, go to the Events page.
3. In the Object Inspector, double click on the box next to OnDrawCell.
This creates an empty procedure TForm1.GridDrawCell.
4. In the source code editor, complete the code for TForm1.GridDrawCell as follows:
procedure TForm1.GridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var S: string; // string displayed in the cell begin S := Grid.Cells[ACol, ARow]; if (Length(S) > 0) and (S = '-') then begin // If first character is a minus sign Grid.Canvas.Font.Color := clRed; Grid.Canvas.TextOut(Rect.Left + 2, Rect.Top + 2, S); end; end;
Note that the above code only works correctly if each cell contains a string representing a VALID
That's because a StringGrid doesn't store "numbers" for display in its cells, it stores the strings to be displayed. In other words, the content of a cell can be: