Right-aligned labels in WinForms

The most obvious way to right-align a Label in WinForms doesn't work: setting anchor to Top/Bottom Right and TextAlign to TopRight. If the text changes the label's Left coordinate remains unchanged instead of the Right coordinate (which, one might argue, is a bug).

For this reason I've always used a full-width TableLayoutPanel for right-aligned labels. However this is not always very convenient, depending on the layout in question...

So, I wonder if there are any other ways to keep a Label right-aligned in WinForms that never occurred to me?


One simple option is to disable AutoSize (set to false) and over-size it so there is spare space.

Alternatively, perhaps use Dock instead of just Anchor, although this has a different meaning, so you may need to put it in a Panel or similar). Ultimately this works like the first - by over-sizing it in the first place; so perhaps the first option is simpler.


Using a TableLayoutPanel with docked labels is the only reliable method that I've found for placing right-aligned labels in Winforms. Turning off AutoSize and using oversized labels seems to cause strange anomalies for High DPI users.


Using a FlowLayoutPanel to do it works very well.

flowLayoutPanel.FlowDirection = System.Windows.Forms.FlowDirection.RightToLeft;
flowLayoutPanel2.Controls.Add(label);

Then, just make sure that the flowLayoutPanel is large enough for the label to expand.


Here's what worked for me on a standard form

  • Set AutoSize property off for just the Labels to be right aligned
  • Make all the fields the same size (perhaps this isn't really required) using the Layout toolbar
  • Multi-select the labels and right align them using the Layout toolbar, position where desired
  • Set TextAlign property to one of the xxxRight settings, e.g, TopRight

Well as Sphax noticed you have to:

  1. Set AutoSize to false
  2. Set TextAlign to Right, for example to MiddleRight
  3. Resize label to real size using MeasureString

Code:

label.AutoSize = false; 
label.TextAlign = ContentAlignment.MiddleRight;    

int yourWidthHere = 100;    
using (Graphics g = label.CreateGraphics())    
{    
     SizeF size = g.MeasureString(text, label.Font, yourWidthHere);    
     label.Height = (int)Math.Ceiling(size.Height);    
     label.Text = text;    
}