简体   繁体   中英

c# programmatically add controls adjacently?

When I do this in form load

    TextBox tb1 = new TextBox();
    TextBox tb2 = new TextBox();

    this.Controls.Add(tb1);
    this.Controls.Add(tb2);

It puts one textbox over another (not vertically or horizontally, but covering each other), which is not what I want.

I could manually try to position them programmatically, but is there a way where I can have each control appear adjacently when I add them?

You can use a FlowLayoutPanel .
Here a short example code that you can test using Linqpad

Form f = new Form();
FlowLayoutPanel flp = new FlowLayoutPanel();
flp.Dock = DockStyle.Fill;
flp.FlowDirection = FlowDirection.LeftToRight;
f.Controls.Add(flp);
TextBox t1 = new TextBox();
flp.Controls.Add(t1);
TextBox t2 = new TextBox();
flp.Controls.Add(t2);
f.Show();

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