简体   繁体   中英

Auto positioning controls (without TableLayoutPanel)

My problem is in the picture:

位置

How can i position automatically the next control (textbox in this sample), without a TableLayoutPanel?

Here's a simple example of using a counter to track the number of controls created and compute the proper Y position:

private int counter = 0;

private void button1_Click(object sender, EventArgs e)
{
    counter++;
    int y = counter * 25;

    Label lbl = new Label();
    lbl.Text = "Label " + counter.ToString();
    lbl.Location = new Point(5, y);

    TextBox tb = new TextBox();
    tb.Location = new Point(lbl.Bounds.Right + 5, y);
    this.Controls.Add(lbl);
    this.Controls.Add(tb);
}

Do you mean you want the TextBox move left/right based on the width of Label ?

private void button2_Click(object sender, EventArgs e) {
    int gap1 = textBox1.Left - label1.Right;
    label1.AutoSize = true;
    label1.Text = "long long long long long long long long";
    textBox1.Left = label1.Right + gap1;

    int gap2 = textBox1.Left - label1.Right;
    label2.AutoSize = true;
    label2.Text = "s";
    textBox2.Left = label2.Right + gap2;
}

You firstly record the gap between the TextBox and Label , then set the AutoSize to true , followed by setting the new content of Label , finally you can move the TextBox accordingly.

Before:

之前

After:

后

If you need to align multiple TextBox , or the width of TextBox as well, it would be more complicated, but you can follow the similar logic.

However, you have to write your own code but not doable in the Design view, as the Anchor of control is to the parent container but not the sibling control. Well, in Xcode on Mac you could do this, but AFAIK Visual Studio does not have this feature out of the box.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM