Delphi-PRAXiS

Delphi-PRAXiS (https://www.delphipraxis.net/forum.php)
-   Delphi-News aus aller Welt (https://www.delphipraxis.net/58-delphi-news-aus-aller-welt/)
-   -   Delphi Tip of the Day - Auto Adjust FMX StringGrid Column Widths (https://www.delphipraxis.net/210754-delphi-tip-day-auto-adjust-fmx-stringgrid-column-widths.html)

DP News-Robot 4. Jun 2022 18:40

Delphi Tip of the Day - Auto Adjust FMX StringGrid Column Widths
 
I've been playing around with the FMX StringGrid for the past three weeks. And I thought...
"Wouldn't it be nice if there was a way to automatically resize the column widths based on the values in each of the columns. Just like the way Excel works when you highlight the entire sheet and double-click the thin line between two columns."

In today's Delphi tip of the day I present a simple routine that evaluates the data in each of the column headings and the columns of each row to determine how wide to make the cells. And the best part is, it automatically adjusts all the columns widths in one go.



It's fairly straight forward using two for loops. It loops through each column looking at every row and determining the width that column needs to be based on the data in each cell.



procedure AutoAdjustColumnWidths(const Grid : TStringGrid);
var
col : Integer; //Grid Column
w : single; //New Width
s : string; //Grid Column value
l : Integer; //Lenght of Grid Column value
row : Integer; //Grid Row
r : Single; //Result of TextWidth calculation
begin
for col := 0 to Grid.ColumnCount-1 do
begin
w := 0;
s := Grid.ColumnByIndex(col).Header;
l := length(s);
w := Grid.TextWidthToColWidth(l,s) * 1.05; //add a little padding
for row := 0 to Grid.RowCount-1 do
begin
s := Grid.Cells[col,row];
l := length(s);
r := Grid.TextWidthToColWidth(l,s) * 1.05; //add a little padding
if r > w then
w := r;
end;
Grid.Columns[col].Width := w;
end;
end;
I'm sure this can be improved upon so it only evaluates the first 50 or 100 rows. I'll leave that up to you to figure out.

Enjoy,
Gunny Mike
https://zilchworks.com


















Weiterlesen...


Alle Zeitangaben in WEZ +1. Es ist jetzt 18:39 Uhr.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024 by Thomas Breitkreuz