Hi how can we get word wrap functionality to a label in winforms?
I place a label in a panel and added some text to label dyanamically. But it exceeds the panel length. How can i solve this?
Thanks in advance
Hi how can we get word wrap functionality to a label in winforms?
I place a label in a panel and added some text to label dyanamically. But it exceeds the panel length. How can i solve this?
Thanks in advance
The quick answer: switch off AutoSize.
The big problem here is that the label will not change it's 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:
You will also need to set the ResizeRedraw style flag in the constructor.
As Jonathan said, you need to switch AutoSize off. But I see no reason to handle painting as you can set label's vertical extent to a convenient value (aka not overlapping other controls but able to hold the largest dynamic text) and it will do the word wrap just fine.
What could do any custom painting better than this?
EDIT: actually, wether to handle painting or not is a question of preference: would you prefer the label overlap other controls or have its text truncated sometimes?
Found on msdn: http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/97c18a1d-729e-4a68-8223-0fcc9ab9012b
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();
}
}
Actually, the accepted answer is incorrect.
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.MaximimSize = new Size(100, 0);
myLabel.AutoSize = true;
Tested and works.