Link to home
Start Free TrialLog in
Avatar of komputer
komputer

asked on

coloring stringgrid

hi,

i am using stringgrid and i would like to color the rows so onDrawCell event i  wrote

mySGrid.Brush.Color := clred;

but it doesnt work.


if you help me, i will be pleased.

thanks.
Avatar of Ivanov_G
Ivanov_G
Flag of Bulgaria image


   The StringGrid has propery DefaultDrawing.

   Set DefaultDrawing = False - for owner draw
ASKER CERTIFIED SOLUTION
Avatar of esoftbg
esoftbg
Flag of Bulgaria image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

After you set DefaultDrawing to False then try this code :

procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
  Rect: TRect; State: TGridDrawState);
begin
  // set the font Bold and Red
  StringGrid1.Canvas.Font.Color := clRed;
  StringGrid1.Canvas.Font.Style := StringGrid1.Canvas.Font.Style + [fsBold];
  // draw the text in the cell
  StringGrid1.Canvas.TextOut (Rect.TopLeft.x, Rect.TopLeft.y,
                              StringGrid1.Cells[ACol, ARow]);
end;
procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
  Rect: TRect; State: TGridDrawState);
const //define your color here.
  clPaleGreen = TColor($CCFFCC);
  clPaleRed = TColor($CCCCFF);

begin

  //Does the cell have the focus you have to paint it with other colors
  if (gdFocused in State) then
  begin
    StringGrid1.Canvas.Brush.Color := clBlack;
    StringGrid1.Canvas.Font.Color := clWhite;
  end
  else //Does the cell have NOT the focus you can use
    //your personal colors here
    if ACol = 2 //the second Column should be
    {//green, the other cells red } then
      StringGrid1.Canvas.Brush.color := clPaleGreen
    else
      StringGrid1.canvas.brush.Color := clPaleRed;

  //Now Paint the cells, but only, if the cell isn't the Title- Row/Column
  //This of course depends whether you have title-Row/Columns or not.

  if (ACol > 0) and (ARow > 0) then
  begin
    //Painting the Background
    StringGrid1.canvas.fillRect(Rect);

    //Painting the Text. Here you can improve the code with
    // using alignment and so on.
    StringGrid1.canvas.TextOut(Rect.Left, Rect.Top, StringGrid1.Cells[ACol, ARow]);
  end;
end;

If you want to colorize your cells depending on values in the cells you can replace the 3 lines (if Acol = 2 ......) with something like this

if StringGrid1.Cells[ACol, ARow] = 'highlight it' then
  StringGrid1.Canvas.Brush.color := clPalered
else
  StringGrid1.canvas.brush.Color := clwhite;