Malfist
Malfist

Reputation: 31815

How to AutoSize the height of a Label but not the width

I have a Panel that I'm creating programmatically; additionally I'm adding several components to it.

One of these components is a Label which will contain user-generated content.

I don't know how tall the label should be, but it does have a fixed width.

How can I set the height so that it displays all the text, without changing the width?

Upvotes: 41

Views: 50860

Answers (3)

circular
circular

Reputation: 301

If you have a label and you want have control over the the vertical fit, you can do the following:

MyLabel.MaximumSize = new Size(MyLabel.Width, 0)
MyLabel.Height = MyLabel.PreferredHeight
MyLabel.MaximumSize = new Size(0, 0)

This is useful for example if you have a label in a container that can be resized. In that case, you can set the Anchor property so that the label is resized horizontally but not vertically, and in the resize event, you can fit the height using the method above.

To avoid the vertical fitting to be interpreted as a new resize event, you can use a boolean:

bool _inVerticalFit = false;

And in the resize event:

if (_inVerticalFit) return;
_inVerticalFit = true;
MyLabel.MaximumSize = new Size(MyLabel.Width, 0)
MyLabel.Height = MyLabel.PreferredHeight
MyLabel.MaximumSize = new Size(0, 0)
_inVerticalFit = false;

Upvotes: 2

Hans Passant
Hans Passant

Reputation: 942267

Just use the AutoSize property, set it back to True.

Set the MaximumSize property to, say, (60, 0) so it can't grow horizontally, only vertically.

Upvotes: 87

Brian
Brian

Reputation: 25834

Use Graphics.MeasureString:

public SizeF MeasureString(
    string text,
    Font font,
    int width
)

The width parameter specifies the maximum value of the width component of the returned SizeF structure (Width). If the width parameter is less than the actual width of the string, the returned Width component is truncated to a value representing the maximum number of characters that will fit within the specified width. To accommodate the entire string, the returned Height component is adjusted to a value that allows displaying the string with character wrap.

In other words, this function can calculate the height of your string based on its width.

Upvotes: 5

Related Questions