0

Delphi: How to make cells' texts in TStringGrid center aligned?

When I use the top code (OnDraw part), it doesn't delete the first text and write the new text on the old text and one sel will duplicate .

Community
  • 1
  • 1
Arash
  • 61
  • 1
  • 2
  • 9

1 Answers1

2

You need to add a call to TCanvas.FillRect before writing out the new text:

procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
  Rect: TRect; State: TGridDrawState);
var
  S: String;
begin
  S := StringGrid1.Cells[ACol, ARow];
  StringGrid1.Canvas.FillRect(Rect);
  SetTextAlign(StringGrid1.Canvas.Handle, TA_CENTER);
  StringGrid1.Canvas.TextRect(Rect,
    Rect.Left + (Rect.Right - Rect.Left) div 2, Rect.Top + 2, S);
end;

Note you'll also have to make sure that the TStringGrid.DefaultDrawing is set to False in order for this to work.

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • thank you but what is the S in your code ? i was changed your code but it dosent worked : – Arash Jul 13 '11 at 00:21
  • procedure TF_avalie_salon.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var S: string; begin S := StringGrid1.Cells[ACol, ARow]; StringGrid1.Canvas.FillRect(Rect); SetTextAlign(StringGrid1.Canvas.Handle, TA_CENTER); StringGrid1.Canvas.TextRect(Rect,Rect.Left + (Rect.Right - Rect.Left) div 2, Rect.Top + 2, S); end; – Arash Jul 13 '11 at 00:21
  • do you want a screen shot from the string grid ? – Arash Jul 13 '11 at 00:22
  • The `S` is something I missed when I grabbed the code from your link. Sorry. – Ken White Jul 13 '11 at 00:25
  • Please add a screenshot to your original question, as it appears I don't understand what the problem is at this point. `FillRect` should solve the problem (unless you're forgetting to set the `StringGrid.DefaultDrawing` to False). – Ken White Jul 13 '11 at 00:28
  • yoohoo :D it works now . i didnt forget to set DefaultDrawing to false , i didnt knew it , thank you dear . you solve my problem perfectly – Arash Jul 13 '11 at 00:51
  • why i cant ask it admin ? subject : delphi : move between cells of string grid buddy : thank you all for solving my problems and sorry for my many questions how can i move between cells of a string grid in delphi by tab or arrow keys . as you know , string grid in delphi has only one tab order but i need move between cells by arrow kes or tab for more comfortable and user friendly . i was tried to use KeyPress event but this event only knows chars and dosent know control keys like tab and ... tags : delphi tab-ordering cells tabs arrow error : It does not meet our quality standards. – Arash Jul 13 '11 at 10:16
  • @user: That's a totally separate question, and should be posted as a new one. It has nothing to do with this question. @Downvoter: Padding, because of the way `TextRect`works. I just took it from the previously posted code from the original question's link, so I don't know how 2px was determined. – Ken White Jul 13 '11 at 11:08