2

Is there any way to paint specific cells on Delphi's TStringGrid without using the OnDrawCell event, for instance if I click a button the specified cells will be painted depending on their content.

Raul
  • 656
  • 5
  • 17

3 Answers3

11

To keep the painting persistent, the way you should do this is as follows:

  • in the button OnClick event handler, set some data that distinguishes these cells
  • in the same event handler, invalidate the painting area of cells
  • in OnDrawCell event handler do a normal painting for the cells not distinguished
  • in the same event handler, paint your distinguished cells differently

--jeroen

Uli Gerhardt
  • 13,748
  • 1
  • 45
  • 83
Jeroen Wiert Pluimers
  • 23,965
  • 9
  • 74
  • 154
3

No, that is not possible. The next time Windows decides to redraw the control (something you can't really control), everything you have drawn will be overpainted by the Control's Paint method and all painting-related events.

You have to use the event approach to do custom painting like that as Jeroen points out.

jpfollenius
  • 16,456
  • 10
  • 90
  • 156
1
procedure TForm1.Button1Click(Sender: TObject);
var aRect: TRect;
begin
  aRect := StringGrid1.CellRect(2,2);

  StringGrid1.Canvas.Brush.Color := clBlue; 
  StringGrid1.Canvas.FillRect(aRect);
  StringGrid1.Canvas.Font.Color := clBlack;
  StringGrid1.Canvas.TextOut(aRect.Left + 2 , aRect.Top + 2, StringGrid1.Cells[2, 2]);
end;
SimaWB
  • 9,246
  • 2
  • 41
  • 46
  • 3
    this won't persist past the next paint cycle – David Heffernan Dec 20 '10 at 07:36
  • 2
    @raul I very much doubt that. Jeroen has given you the answer. You need to understand the Windows painting mechanisms before you can appreciate the issues here. – David Heffernan Dec 20 '10 at 08:40
  • @david what I want is avoid putting my code in the OnDrawCell as per my problem requirments, that is why I cannot use Jeroen's solution, but please if you can provide more details about the painting mechanisms that will help everyone who reads this thread. – Raul Dec 20 '10 at 14:28
  • @Raul No, you need to do it in OnDrawCell. It won't work anywhere else. You problem requirement is not attainable! If you don't know about the Windows paint cycle then I recommend you read Petzold's seminal book on Windows Programming. – David Heffernan Dec 20 '10 at 15:13
  • Ok Mr. Heffernan, I'll try to find out another way to solve my problem as painting the grid for outside the event is getting overridden as soon as the grid is redrawn, thank you for your support. – Raul Dec 20 '10 at 15:23
  • 1
    @Raul "painting the grid for outside the event is getting overridden as soon as the grid is redrawn" - that's what I was trying to get across in my original comment to this answer! – David Heffernan Dec 20 '10 at 17:06
  • @Raul Also, you ought to accept Jeroen's answer - it's the best one. – David Heffernan Dec 20 '10 at 17:07