Board index » cppbuilder » Auto-fit columns in a TStringGrid

Auto-fit columns in a TStringGrid


2005-02-02 11:18:11 PM
cppbuilder48
I have a TStringGrid and I'd like to auto-fit the columns to their
content. Like Excel's capability.
Any ideas?
Thanks,
tim
 
 

Re:Auto-fit columns in a TStringGrid

Just use a looping system, like this :
/* Untested Code */
int Col, Row, ColCount, RowCount, MaxLen, TempLen;
ColCount = StringGrid1->ColCount;
RowCount = StringGrid1->RowCount;
for(Col=0;Col<ColCount;Col++){
MaxLen = 0;
for(Row=0;Row<RowCount;Row++){
TempLen = StringGrid1->Cells[Col][Row].Length();
if(TempLen>MaxLen)
MaxLen = TempLen;
}
if(MaxLen == 0){
// Reset to default size;
StringGrid->ColWidths[Col] = 50;
}else{
// Set to largest string size.
StringGrid->ColWidths[Col] = Canvas->TextWidth("O") * MaxLen + 5;
}
}
Hope this helps.
--
Jonathan
"tim" < XXXX@XXXXX.COM >wrote in message
Quote
I have a TStringGrid and I'd like to auto-fit the columns to their content.
Like Excel's capability.

Any ideas?



Thanks,


tim
 

Re:Auto-fit columns in a TStringGrid

Perfect.
I'm sad to say I didn't think about the correspondence between the
cell's AnsiString length and the column size. At any rate, this worked
almost straight cut and paste (obvious name changes to protect the
innocent).
Thanks for the time and effort.
cheers,
tim
Jonathan Benedicto wrote:
Quote
Just use a looping system, like this :

/* Untested Code */

int Col, Row, ColCount, RowCount, MaxLen, TempLen;

ColCount = StringGrid1->ColCount;
RowCount = StringGrid1->RowCount;

for(Col=0;Col<ColCount;Col++){
MaxLen = 0;
for(Row=0;Row<RowCount;Row++){
TempLen = StringGrid1->Cells[Col][Row].Length();
if(TempLen>MaxLen)
MaxLen = TempLen;
}
if(MaxLen == 0){
// Reset to default size;
StringGrid->ColWidths[Col] = 50;
}else{
// Set to largest string size.
StringGrid->ColWidths[Col] = Canvas->TextWidth("O") * MaxLen + 5;
}
}

Hope this helps.

 

{smallsort}

Re:Auto-fit columns in a TStringGrid

I'm glad it worked, and that I could help you.
--
Jonathan
"tim" < XXXX@XXXXX.COM >wrote in message
Quote
Perfect.

I'm sad to say I didn't think about the correspondence between the cell's
AnsiString length and the column size. At any rate, this worked almost
straight cut and paste (obvious name changes to protect the innocent).

Thanks for the time and effort.



cheers,



tim




Jonathan Benedicto wrote:
>Just use a looping system, like this :
>
>/* Untested Code */
>
>int Col, Row, ColCount, RowCount, MaxLen, TempLen;
>
>ColCount = StringGrid1->ColCount;
>RowCount = StringGrid1->RowCount;
>
>for(Col=0;Col<ColCount;Col++){
>MaxLen = 0;
>for(Row=0;Row<RowCount;Row++){
>TempLen = StringGrid1->Cells[Col][Row].Length();
>if(TempLen>MaxLen)
>MaxLen = TempLen;
>}
>if(MaxLen == 0){
>// Reset to default size;
>StringGrid->ColWidths[Col] = 50;
>}else{
>// Set to largest string size.
>StringGrid->ColWidths[Col] = Canvas->TextWidth("O") * MaxLen + 5;
>}
>}
>
>Hope this helps.
>