Re: Center text in cell of stringgrid

Posted by webmaster Guido on July 26, 2008

In Reply to Center text in cell of stringgrid posted by Harry D. P16510 on July 25, 2008

: Is it possible to center text in the cells of a Delphi TStringGrid component? If yes, how to program this, for example only for the second column of the grid?

In the OnDrawCell event handler, we set the text-alignment of the stringgrid's canvas with the Windows API function SetTextAlign(CanvasHandle, AlignmentMode). The return value of this function is the previous text-alignment setting; we save it temporarily.

Next, we write the contents of the cell with Canvas.TextRect(Rect, X, Y, S). Any portions of the string S that fall outside the rectangle passed in the Rect parameter are clipped. The upper left corner of the text is placed at the point (X, Y).

Finally, we reset the text-alignment to the saved value.

Here's a Delphi source code example:

procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
  Rect: TRect; State: TGridDrawState);
var
  S: string;
  SavedAlign: word;
begin
  if ACol = 1 then begin  // ACol is zero based
    S := StringGrid1.Cells[ACol, ARow]; // cell contents
    SavedAlign := SetTextAlign(StringGrid1.Canvas.Handle, TA_CENTER);
    StringGrid1.Canvas.TextRect(Rect,
      Rect.Left + (Rect.Right - Rect.Left) div 2, Rect.Top + 2, S);
    SetTextAlign(StringGrid1.Canvas.Handle, SavedAlign);
  end;
end; 

If you want right-aligned column, use the following source code:

procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
  Rect: TRect; State: TGridDrawState);
var
  S: string;
  SavedAlign: word;
begin
  if ACol = 1 then begin
    S := StringGrid1.Cells[ACol, ARow]; // cell contents
    SavedAlign := SetTextAlign(StringGrid1.Canvas.Handle, TA_RIGHT);
    StringGrid1.Canvas.TextRect(Rect, Rect.Right - 2, Rect.Top + 2, S);
    SetTextAlign(StringGrid1.Canvas.Handle, SavedAlign);
  end;
end; 

Related articles

Annoying StringGrid Focus
... setting the focus on the upper lefthand cell [0,0] and coloring it dark blue. This obfuscates what i want to show in that cell...
Change cell colours
How to set up arrays for FG and BG colours of stringgrid cells
Coloured text in stringgrid
Put differently coloured strings *within one cell*: part 1 red, part 2 blue,...
 

Follow Ups