[c#] Word wrap for a label in Windows Forms

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

This question is related to c# .net winforms label controls

The answer is


Use style="overflow:Scroll" in the label as in the below HTML. This will add the scroll bar in the label within the panel.

<asp:Label
    ID="txtAOI"
    runat="server"
    style="overflow:Scroll"
    CssClass="areatext"
    BackColor="White"
    BorderColor="Gray"
    BorderWidth="1"
    Width = "900" ></asp:Label>

There is no autowrap property but this can be done programmatically to size it dynamically. Here is one solution:

  • Select the properties of the label

  • AutoSize = True

  • MaximumSize = (Width, Height) where Width = max size you want the label to be and Height = how many pixels you want it to wrap

    Sample Properties


  1. Put the label inside a panel
  2. 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);
    }
    
  3. Set Auto-Size for the label to true

  4. Set Dock for the label to Fill

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 had to find a quick solution, so I just used a TextBox with those properties:

var myLabel = new TextBox
                    {
                        Text = "xxx xxx xxx",
                        WordWrap = true,
                        AutoSize = false,
                        Enabled = false,
                        Size = new Size(60, 30),
                        BorderStyle = BorderStyle.None,
                        Multiline =  true,
                        BackColor =  container.BackColor
                    };

This helped me in my Form called InpitWindow: In Designer for Label:

AutoSize = true;
Achors = Top, Left, Right.

private void InputWindow_Shown(object sender, EventArgs e) {
    lbCaption.MaximumSize = new Size(this.ClientSize.Width - btOK.Width - btOK.Margin.Left - btOK.Margin.Right -
        lbCaption.Margin.Right - lbCaption.Margin.Left, 
        Screen.GetWorkingArea(this).Height / 2);
    this.Height = this.Height + (lbCaption.Height - btOK.Height - btCancel.Height);
    //Uncomment this line to prevent form height chage to values lower than initial height
    //this.MinimumSize = new Size(this.MinimumSize.Width, this.Height);
}
//Use this handler if you want your label change it size according to form clientsize.
private void InputWindow_ClientSizeChanged(object sender, EventArgs e) {
    lbCaption.MaximumSize = new Size(this.ClientSize.Width - btOK.Width - btOK.Margin.Left * 2 - btOK.Margin.Right * 2 -
        lbCaption.Margin.Right * 2 - lbCaption.Margin.Left * 2,
        Screen.GetWorkingArea(this).Height / 2);
}

Whole code of my form


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


Not sure it will fit all use-cases but I often use a simple trick to get the wrapping behaviour: put your Label with AutoSize=false inside a 1x1 TableLayoutPanel which will take care of the Label's size.


If you really want to set the label width independent of the content, I find that the easiest way is this:

  • Set autosize true
  • Set maximum width to how you want it
  • Set minimum width identically

Now the label is of constant width, but it adapts its height automatically.

Then for dynamic text, decrease the font size. If necessary, use this snippet in the sub where the label text is set:

If Me.Size.Height - (Label12.Location.Y + Label12.Height) < 20 Then
    Dim naam As String = Label12.Font.Name
    Dim size As Single = Label12.Font.SizeInPoints - 1
    Label12.Font = New Font(naam, size)
End If

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 a new 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#:

label.Anchor = AnchorStyles.Left | AnchorStyles.Right;
label.AutoSize = true;

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.

myLabel.MaximumSize = new Size(100, 0);
myLabel.AutoSize = true;

Tested and works.


From MSDN, Automatically Wrap Text in Label:

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();
    }
}

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.


The simple answer for this problem is to change the DOCK property of the Label. It is "NONE" by default.


Have a better one based on @hypo 's answer

public class GrowLabel : Label {
    private bool mGrowing;
    public GrowLabel() {
        this.AutoSize = false;
    }
    private void resizeLabel() {
        if (mGrowing)
            return;
        try {
            mGrowing = true;
            int width = this.Parent == null ? this.Width : this.Parent.Width;

            Size sz = new Size(this.Width, Int32.MaxValue);
            sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
            this.Height = sz.Height + Padding.Bottom + Padding.Top;
        } 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();
    }
}

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.


If the dimensions of the button need to be kept unchanged:

myButton.Text = "word\r\nwrapped"

Set the AutoEllipsis Property to 'TRUE' and AutoSize Property to 'FALSE'.

enter image description here

enter image description here


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to label

How to set label size in Bootstrap How do I change the text size in a label widget, python tkinter Change grid interval and specify tick labels in Matplotlib Editing legend (text) labels in ggplot How to change Label Value using javascript React ignores 'for' attribute of the label element How to dynamically update labels captions in VBA form? why I can't get value of label with jquery and javascript? What does "for" attribute do in HTML <label> tag? Get Application Name/ Label via ADB Shell or Terminal

Examples related to controls

What is Dependency Injection and Inversion of Control in Spring Framework? Change the location of an object programmatically How to access Winform textbox control from another class? How to make overlay control above all other controls? How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)? How can I change the Java Runtime Version on Windows (7)? How can I make visible an invisible control with jquery? (hide and show not work) DataGridView - how to set column width? Get a Windows Forms control by name in C# C# Get a control's position on a form