Word wrap for a label in Windows Forms
Actually, the accepted answer is unnecessarily complicated.
If you set the label to AutoSize, it will automatically grow with whatever text you put in it. (This includes vertical growth.)
If you want to make it word wrap at a particular width, you can set the MaximumSize property.
myLabel.MaximumSize = new Size(100, 0);
myLabel.AutoSize = true;
Tested and works.
The quick answer: switch off AutoSize.
The big problem here is that the label will not change its height automatically (only width). To get this right you will need to subclass the label and include vertical resize logic.
Basically what you need to do in OnPaint is:
- Measure the height of the text (Graphics.MeasureString).
- If the label height is not equal to the height of the text set the height and return.
- Draw the text.
You will also need to set the ResizeRedraw style flag in the constructor.
In my case (label on a panel) I set label.AutoSize = false
and label.Dock = Fill
.
And the label text is wrapped automatically.
There is no autowrap property but this can be done programmatically to size it dynamically. Here is one solution:
-
Select the properties of the label
-
AutoSize
=True
-
MaximumSize
= (Width, Height) where Width = max size you want the label to be and Height = how many pixels you want it to wrap
From MSDN, Automatically Wrap Text in Label:
using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
public class GrowLabel : Label {
private bool mGrowing;
public GrowLabel() {
this.AutoSize = false;
}
private void resizeLabel() {
if (mGrowing)
return;
try {
mGrowing = true;
Size sz = new Size(this.Width, Int32.MaxValue);
sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
this.Height = sz.Height;
}
finally {
mGrowing = false;
}
}
protected override void OnTextChanged(EventArgs e) {
base.OnTextChanged(e);
resizeLabel();
}
protected override void OnFontChanged(EventArgs e) {
base.OnFontChanged(e);
resizeLabel();
}
protected override void OnSizeChanged(EventArgs e) {
base.OnSizeChanged(e);
resizeLabel();
}
}