Posted by webmaster Guido on January 31, 2009
In Reply to Re: Setting StringGrid.Height posted by Lee p12462 on
January 28, 2009
: : : I have a StringGrid that I populate on the fly. Once I'm done populating it, I
want to set the .height property such that the bottom border is just below the [possible horizontal
scroll bar and] last line in the StringGrid. (...)
: : Well, the total height of a StringGrid component
is influenced by: (...)
: : So, it's not easy to calculate the exact total height. I'm testing some combinations, just give me some time ;)
: Thanks Guido!
: Well, it isn't scientific but, I experimented by just adding a "fudge factor" for each line. I found
by adding 8 to the StringGrid1.Canvas.TextHeight for each row, it comes close enough for what I need! (...)
: Don't spend much time on this but if you come up with something close, I'd like to see it. Having
a vertical scroll bar would be OK :-)
: Thank you very much for your time and effort :-)
: Lee
As
promised, I've been playing around with code for automatically resizing a stringgrid. Hope you and other
Delphi programmers find it useful :)
Here's an example procedure:
{ Resize the height of stringgrid, depending on its number of rows, but staying between a preset minimal and maximal height. } procedure TForm1.ResizeGridHeight(G: TStringGrid; HMin, HMax: integer); var Grid: TStringGrid; begin if G is TStringGrid then Grid := G as TStringGrid else exit; // safety net to avoid crashes while Grid.GridHeight >= Grid.ClientHeight do Grid.Height := Grid.Height + 2; while Grid.GridHeight < Grid.ClientHeight - 5 do Grid.Height := Grid.Height - 2; if Grid.Height < HMin then Grid.Height := HMin; if Grid.Height > HMax then Grid.Height := HMax; end;
Somewhere in your code, you fill the StringGrid. Immediately after that, call the procedure above. For example, limiting the height from 70 to 300 pixels:
ResizeGridHeight(StringGrid1, 70, 300);
Related articles