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 lab
Attach an event handler to the labels' SizeChanged event:
private void label1_SizeChanged(object sender, EventArgs e)
{
label1.Location = new Point(Your_Anchor_Point - label1.Width, label1.Location.Y);
}
To be more DPI friendly consider using some other control as the anchor point, i.e.
label1.Location = new Point(dataGridView1.Location.X + dataGridView1.Width - label1.Width, label1.Location.Y);
to align to the RH side of the dgv.
(BTW: I tried the Paint & TextChanged events but they seemed to sometimes get confused - probably something to do with event order particularly on opening a new form.)
The best solution for me was:
Here's what worked for me on a standard form
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.
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.
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);