I'm trying to get the text in my StringGrid to center. After some research I came up with this function posted by someone else here that when used on DefaultDraw:False should work.
procedure TForm1.StringGrid2DrawCell(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;
However if I set DefaultDraw:False, the StringGrid just appears glitchey.
The lines in the function that fill the StringGrid with text is
Sg.RowCount := Length(arrpos);
for I := 0 to (Length(arrpos) - 1) do
begin
sg.Cells[0,i] := arrpos[i];
sg.Cells[1,i] := arrby[i];
end;
arrpos and arrby are arrays of string. sg is the StringGrid.
I need after that has been executing the text to appear in the center on the cell.
UPDATE
For those suffering from similar problems one of the key issues with this piece of code is if the if statement
if ACol = 1 then begin
That line means it will only run the code for column 1 e.g. the second column since StringGrid is 0 based. You can safely remove the if statement and it will execute and work WITHOUT having to disable default drawing.
this works in my test
procedure TForm1.sgDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect;
State: TGridDrawState);
var
LStrCell: string;
LRect: TRect;
begin
LStrCell := sg.Cells[ACol, ARow]; // grab cell text
sg.Canvas.FillRect(Rect); // clear the cell
LRect := Rect;
LRect.Top := LRect.Top + 3; // adjust top to center vertical
// draw text
DrawText(sg.Canvas.Handle, PChar(LStrCell), Length(LStrCell), LRect, DT_CENTER);
end;