Determine Label Size based upon amount of text and font size in Winforms/C#
Solution 1:
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;
}
Solution 2:
System.Drawing.Graphics has a MeasureString method that you can use for this purpose. Use the overload that takes a string, a font, and an int "width" parameter; this last parameter specifies the maximum width allowed for the string - use the set width of your label for this parameter.
MeasureString returns a SizeF object. Use the Height property of this returned object to set the height of your label.
Note: to get a Graphics object for this purpose, you can call this.CreateGraphics.
Solution 3:
Graphics.MeasureString() will probably help you.
This is also one of the only usecases for using the Control.CreateGraphics() call!
Solution 4:
Size maxSize = new Size(495, int.MaxValue);
_label.Height = TextRenderer.MeasureText(_label.Text , _label.Font, maxSize).Height;