Word wrap for a label in Windows Forms

Viewed 194372

How can one get word wrap functionality for a Label for text which goes out of bounds?

20 Answers

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:

  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.

In my case (label on a panel) I set label.AutoSize = false and label.Dock = Fill. And the label text is wrapped automatically.

If you are entering text into the label beforehand, you can do this.

  1. In the designer, Right-Click on the label and click Properties.
  2. In Properties, search for text tab.
  3. Click in the tab and click on the arrow button next to it.
  4. A box will popup on top of it.
  5. You can press enter in the popup box to add lines and type as in notepad! (PRESS ENTER WHERE YOU WANT TO WRAP THE LABEL TEXT)

I would recommend setting AutoEllipsis property of label to true and AutoSize to false. If text length exceeds label bounds, it'll add three dots (...) at the end and automatically set the complete text as a tooltip. So users can see the complete text by hovering over the label.

I have a label that autowraps and grows to whatever size in a right docked autosize panel, whose width is set by other content.

Label (in tablelayoutpanel) Autosize = True.

TableLayoutPanel (in panel) Autosize = True, AutoSizeMode = GrowAndShrink, Dock = Bottom, one Column SizeType = 100%, one Row SizeType = 100%.

Panel (right docked in form) AutoSize = True, AutoSizeMode = GrowAndShrink, Dock = Right.

Use System.Windows.Forms.LinkLabel instead of Label and set the property LinkArea as below.

myLabel.LinkArea = new LinkArea(0, 0);
Related