Label word wrapping
C#WinformsC# 4.0C# 3.0C# Problem Overview
C# Solutions
Solution 1 - C#
Change your maximum size,
label1.MaximumSize = new Size(100, 0);
And set your autosize to true.
label1.AutoSize = true;
That's it!
Solution 2 - C#
Just set Label AutoSize property to False. Then the text will be wrapped and you can re-size the control manually to show the text.
Solution 3 - C#
Refer to Automatically Wrap Text in Label. It describes how to create your own growing label.
Here is the full source taken from the above reference:
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();
}
}
Solution 4 - C#
Ironically, turning off AutoSize
by setting it to false
allowed me to get the label control dimensions to size it both vertically and horizontally which effectively allows word-wrapping to occur.
Solution 5 - C#
If you open the dropdown for the Text
property in Visual Studio, you can use the enter key to split lines. This will obviously only work for static text unless you know the maximum dimensions of dynamic text.
Solution 6 - C#
If you want some dynamic sizing in conjunction with a word-wrapping label you can do the following:
-
Put the label inside a panel
-
Handle the
ClientSizeChanged event
for the panel, making the label fill the space:private void Panel2_ClientSizeChanged(object sender, EventArgs e) { label1.MaximumSize = new Size((sender as Control).ClientSize.Width - label1.Left, 10000); }
-
Set
Auto-Size
for the label totrue
-
Set
Dock
for the label toFill
Solution 7 - C#
You can use a TextBox
and set multiline
to true
and canEdit
to false
.