Right-aligned labels in WinForms

Viewed 36340

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?

10 Answers

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.

  • dynamically created label's default autosize is false.
  • if label's autosize is false. it contains extra empty space.
  • that tricks you to think its doesnt right align properly. to diagnose it, set the label's backColour to lightgreen

enter image description here

 int rowIndex=1;

 var lbx = new Label();
 lbx.AutoSize = true;          // default is false.
 lbx.BackColor = Color.Green;  // to see if it's aligning or not
 lbx.Text = "Iam  Autosize=true";
 lbx.Anchor = AnchorStyles.Right;
 tlPanel.Controls.Add(lbx, 0, rowIndex);

 var dtp = new DateTimePicker();
 dtp.Anchor = AnchorStyles.Left;
 tlPanel.Controls.Add(dtp, 1, rowIndex);


  //--- row 2  autosize false
 rowIndex=2;
  var lbx2 = new Label();
 lbx2.AutoSize = false;          // default is false.
 lbx2.BackColor = Color.Green;  // to see if it's aligning or not
 lbx2.Text = "AutoSz=false";
 lbx2.Anchor = AnchorStyles.Right;
 tlPanel.Controls.Add(lbx2, 0, rowIndex);

 var dtp = new DateTimePicker();
 dtp.Anchor = AnchorStyles.Left;
 tlPanel.Controls.Add(dtp, 1, rowIndex);

Here's an approach that hasn't been mentioned yet.

I worked around a similar issue by not using a Label at all. Instead, you can use a TextBox.

On the TextBox, set the following properties:

BorderStyle = None
BackColor = the color of your form
TextAlign = Right

To suppress any visible cursor or user interaction, add a handler for the Enter event. In there, find another control (could be a hidden label), and call Focus on that:

private void txtFakeLabel_Enter(object sender, EventArgs e)
{
    lblHidden.Focus();
}

This responds very nicely to changing the 'label' text dynamically, as long as you make the control wide enough for the text that will appear there.

Related