How do I keep a label centered in WinForms?

In WinForms I am using a Label to display different messages like success, failure, etc.

I'd like to center that label in the center form. I want a solution that will keep it centered whether there's just one word or a whole sentence in the label.


Solution 1:

Set Label's AutoSize property to False, TextAlign property to MiddleCenter and Dock property to Fill.

Solution 2:

You will achive it with setting property Anchor: None.

Solution 3:

Some minor additional content for setting programmatically:

Label textLabel = new Label() { 
        AutoSize = false, 
        TextAlign = ContentAlignment.MiddleCenter, 
        Dock = DockStyle.None, 
        Left = 10, 
        Width = myDialog.Width - 10
};            

Dockstyle and Content alignment may differ from your needs. For example, for a simple label on a wpf form I use DockStyle.None.

Solution 4:

If you don't want to dock label in whole available area, just set SizeChanged event instead of TextChanged. Changing each letter will change the width property of label as well as its text when autosize property set to True. So, by the way you can use any formula to keep label centered in form.

private void lblReport_SizeChanged(object sender, EventArgs e)
{
    lblReport.Left = (this.ClientSize.Width - lblReport.Size.Width) / 2;
}