Reputation: 61
I want to create a StringGrid in Delphi. But if a string gets too long, the string gets cut off:
I want to see the entire String. The length of the String can change, since the user can enter text in the StringGrid himself, so I can't just set the ColWidths
to a certain integer.
Is there a way to adjust the ColWidths
with the largest String in the Column?
Upvotes: 1
Views: 587
Reputation: 51
I like above code flowing is update for general
procedure CalcGridColumnWidth(var StringGrid:TStringGrid;const WhichCol: Integer);
var
i, Temp, Longest: Integer;
const
Padding = 20;
begin
Longest := StringGrid.Canvas.TextWidth(StringGrid.Cells[WhichCol, 0]);
for i := 1 to StringGrid.RowCount - 1 do
begin
Temp := StringGrid.Canvas.TextWidth(StringGrid.Cells[WhichCol, i]);
if Temp > Longest then
Longest := Temp;
end;
StringGrid.ColWidths[WhichCol] := Longest + Padding;
end;
Upvotes: 0
Reputation: 125749
You can calculate the width needed for the string in each cell using the StringGrid's canvas by calling TextWidth
.
Here's a quick sample to demonstrate. I'm doing everything in code for simplicity - the StringGrid is set up in the form's OnCreate
, but of course that's only for demonstration purposes. To run the sample below, create a new VCL Forms Application, drop a TStringGrid
on the form, and add the code below. I've set it up so you can use it on any column by passing that column's index to the function CalcColumnWidth
. The const Padding
is to add space on the right side of the column - adjust that to whatever value suits your needs.
If the user can edit the cell contents, you'll just need to call the CalcColumnWidth
function after that edit to recalculate the column width.
procedure TForm1.FormCreate(Sender: TObject);
begin
StringGrid1.FixedRows := 0;
StringGrid1.FixedCols := 0;
StringGrid1.ColCount := 2;
StringGrid1.RowCount := 4;
StringGrid1.ColCount := 2;
StringGrid1.Cells[0, 0] := '1';
StringGrid1.Cells[1, 0] := 'Some text here';
StringGrid1.Cells[0, 1] := '2';
StringGrid1.Cells[1, 1] := 'Some other text here';
StringGrid1.Cells[0, 2] := '3';
StringGrid1.Cells[1, 2] := 'A longer string goes here';
StringGrid1.Cells[0, 3] := '4';
StringGrid1.Cells[1, 3] := 'Shortest';
CalcColumnWidth(1);
end;
procedure TForm1.CalcColumnWidth(const WhichCol: Integer);
var
i, Temp, Longest: Integer;
const
Padding = 20;
begin
Longest := StringGrid1.Canvas.TextWidth(StringGrid1.Cells[WhichCol, 0]);
for i := 1 to StringGrid1.RowCount - 1 do
begin
Temp := StringGrid1.Canvas.TextWidth(StringGrid1.Cells[WhichCol, i]);
if Temp > Longest then
Longest := Temp;
end;
StringGrid1.ColWidths[WhichCol] := Longest + Padding;
end;
Upvotes: 5