It seems something obvious to have. I want the texts to be in the center of the cell, but for some reason I can't find it in properties. How can I do this?
+7
A:
There's no property to center the text in TStringGrid, but you can do that at DrawCell event as:
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;
The code I posted from here
UPDATE:
to center text while writing in the cell, add this code to GetEditText
Event:
procedure TForm1.StringGrid1GetEditText(Sender: TObject; ACol, ARow: Integer;
var Value: string);
var
S : String;
I: Integer;
IE : TInplaceEdit ;
begin
for I := 0 to StringGrid1.ControlCount - 1 do
if StringGrid1.Controls[i].ClassName = 'TInplaceEdit' then
begin
IE := TInplaceEdit(StringGrid1.Controls[i]);
ie.Alignment := taCenter
end;
end;
Mohammed Nasman
2010-08-22 08:00:33
Thanks. So, if I want it to be centered as the user writes in its cells, then I should do this in onEdit()?
Flom Enol
2010-08-22 08:07:24
The code above is implemented in the `OnDrawCell` event and should be left there. If you want the the input to be centered as the user center's it, then you should use the editors TEdit/TWhateverEdit's paint events for that.
Aldo
2010-08-22 10:15:35
Flom, I have updated the answer.
Mohammed Nasman
2010-08-22 13:11:45
Thanks Mohammed. That is a good way to implement it. I was wondering, isn't there a better component for adding/editing data in a table like StringGrid? Because StringGrid is somehow limited in features.
Flom Enol
2010-08-24 08:26:48
Mohammed Nasman
2010-08-24 08:41:15