views:

2500

answers:

4

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

+10  A: 

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:

  1. Measure the height of the text (Graphics.MeasureString).
  2. If the label height is not equal to the height of the text set the height and return.
  3. Draw the text.

You will also need to set the ResizeRedraw style flag in the constructor.

Jonathan C Dickinson
Thank you i got some idea. I'll try to implement it
Nagu
A: 

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?

Sorin Comanescu
A: 

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();
  }
}
hypo
In order to break on characters rather than words (useful when you have long strings without spaces such as file paths), use (TextFormatFlags.WordBreak | TextFormatFlags.TextBoxControl) instead. See the last post in the same MSDN thread.
ohadsc
+1  A: 

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.

John Gietzen