Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I keep a label centered in WinForms?

People also ask

How do I center a label in Visual Basic?

Set the Autosize property of your label to False, then either Dock the Label Top, Bottom or Fill, or drag it to the full width of the form and set Anchor to both Left and Right. Then set TextAlign to MiddleCenter.

How do you center a form in C#?

Use Form. CenterToScreen() method. On system with two monitors the form will be centered on one that currently have the cursor.


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


You will achive it with setting property Anchor: None.


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.


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

The accepted answer didn't work for me for two reasons:

  1. I had BackColor set so setting AutoSize = false and Dock = Fill causes the background color to fill the whole form
  2. I couldn't have AutoSize set to false anyway because my label text was dynamic

Instead, I simply used the form's width and the width of the label to calculate the left offset:

MyLabel.Left = (this.Width - MyLabel.Width) / 2;