2

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.

2
  • I've just tried your code and it works fine. (Delphi 5 and 10 @Win7) Commented Jan 18, 2011 at 9:23
  • The problem with the code was that the procedure is for StringGrid2 however in the code it's listed as StringGrid1. Another reason I hate delphi auto-complete.However I THINK Dorin Duminica's method is more efficient anyway. Commented Jan 18, 2011 at 20:45

1 Answer 1

6

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.