I'd like to know if there's a better approach to this problem. I want to resize a label (vertically) to accomodate certain amount of text. My label has a fixed width (about 60 chars wide before it must wrap), about 495 pixels. The font is also a fixed size (12points afaik), but the text is not.
What I want to do is increase the Label Height when there's a "NewLine" or the text must wrap; the idea is that the text is fully visible in the label. The AutoSize doesn't work because it will grow in width, not in height.
Of course I could count the number of NewLines and add: Newlines * LineHeight, and then -given that I manage to put 60 chars per line, just divide the number of chars and add as many LineHeight pixels as needed.
I was wondering if there was a more professional way to do it. Is my approach too "lame" ?
Thanks in advance.
The AutoSize property helps you size the controls to fit larger or smaller captions, which is particularly useful if the caption will change at run time.
How about Graphics.MeasureString
, with the overload that accepts a string, the font, and the max width? This returns a SizeF
, so you can round round-off the Height
.
using(Graphics g = CreateGraphics()) { SizeF size = g.MeasureString(text, lbl.Font, 495); lbl.Height = (int) Math.Ceiling(size.Height); lbl.Text = text; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With