How can we get word wrap functionality for a label in Windows Forms?
I placed a label in a panel and added some text to label dynamically. But it exceeds the panel length. How can I solve this?
How can we get word wrap functionality for a label in Windows Forms?
I placed a label in a panel and added some text to label dynamically. But it exceeds the panel length. How can I solve this?
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.
Tested and works.
Bad news: there is not an autowrap property.
Good news: there is a light at the end of the tunnel!
You could accomplish this programmatically to size it dynamically, but here is the easiest solution:
MaximumSize = (Width, Height) where Width = max size you want the label to be and Height = how many pixels you want it to wrap
Not sure it will fit all use-cases but I often use a simple trick to get the wrapping behaviour: put your
Label
withAutoSize=false
inside a 1x1TableLayoutPanel
which will take care of theLabel
's size.If your panel is limiting the width of your label, you can set your label’s Anchor property to Left, Right and set AutoSize to true. This is conceptually similar to listening for the Panel’s
SizeChanged
event and updating the label’s MaximumSize to anew Size(((Control)sender).Size.Width, 0)
as suggested by a previous answer. Every side listed in the Anchor property is, well, anchored to the containing Control’s respective inner side. So listing two opposite sides in Anchor effectively sets the control’s dimension. Anchoring to Left and Right sets the Control’s Width property and Anchoring to Top and Bottom would set its Height property.This solution, as C#:
If the dimensions of the button need to be kept unchanged:
Have a better one based on @hypo 's answer
int width = this.Parent == null ? this.Width : this.Parent.Width;
this allows you to use auto-grow label when docked to a parent, e.g. a panel.this.Height = sz.Height + Padding.Bottom + Padding.Top;
here we take care of padding for top and bottom.