views:

16

answers:

1

Hi all.

Right now I clarify this may be a duplicated question from: http://stackoverflow.com/questions/1692383/right-aligned-labels-in-winforms But non of the answers satisfied me.

The problem is very simple:

I have a right aligned label with autosize setted to true. The expected behavor is that when the text is increased the right coordinate remain unchanged. But that is not what it happens. The left coordinate is the one wich remains unchanged.

My app is kind of small, so I don't want to start putting controls into panels and so.. So I've tried all solutions that involved ONLY label properties. The only one wich worked is to set autosize to false and over-size it. (Accepted solution of question Nº1692383). But it is really ugly!!! I'd realy like to avoid that.

Any other posible solution??

Thanks in advance!

+1  A: 

One solution would be to capture the label's right margin in the form constructor, and in the label SizeChanged event, reset the location based on the initial right margin, the label's current Width and the label Parent's current Width.

This also assumes the label is anchored on the right to handle form resizing.

private readonly int _rightMargin;

public Form1()
{
    InitializeComponent();

    _rightMargin = label1.Parent.Width - label1.Right;
}

private void label1_SizeChanged(object sender, EventArgs e)
{
    label1.Location = new Point(label1.Parent.Width - _rightMargin - label1.Width, label1.Top);
}
adrift