如何动态添加成对的控件

How to dynamically add pairs of controls

我正在尝试向表单动态添加一些控件(目前是 文本框 标签 )。没有一定数量的要绘制的对。

我正在努力实现的示例。

如您所见,table 用完了 space,所以它移到了右边。

目前,我在 FlowLayoutPanel 中使用 TableLayoutPanel
Column 0 包含 labelcolumn 1 包含 textbox

我如何,或者更确切地说,如何让 FlowLayoutPanel 拆分 table?

private void Form1_Load(object sender, EventArgs e)
{
    FlowLayoutPanel flp = new FlowLayoutPanel()
    {
        Location = new Point(0, 0),
        Dock = DockStyle.Fill,
        AutoSize = false,
        FlowDirection = FlowDirection.TopDown,
        AutoScroll = true,
        BorderStyle = BorderStyle.Fixed3D,
        WrapContents = true
    };

    Controls.Add(flp);

    TableLayoutPanel tlp = new TableLayoutPanel()
    {
        ColumnCount = 2,
        Height = ClientSize.Height,
        BackColor=Color.AliceBlue
    };

    flp.Controls.Add(tlp);

    for (int i = 0; i < 50; i++)
    {
        Label _label = new Label()
        {
            Text = i.ToString("00"),
            AutoSize = true
        };

        tlp.Controls.Add(_label, 0, i);

        TextBox _textbox = new TextBox();
        tlp.Controls.Add(_textbox, 1, i);
    }

可以使用4列的TableLayoutPanel,并为控件设置合适的ColumnStyles

例子

在窗体上放置一个按钮和一个面板,并将面板的锚点设置到所有边缘。然后处理按钮的点击事件并使用此代码:

private void button1_Click(object sender, EventArgs e)
{
    var fields = new string[] { "A Field", "Some Field", "Another Field",
        "A Long Field Name", "A Long Long Field Name" };
    var tlp = new TableLayoutPanel() { Dock = DockStyle.Fill, ColumnCount = 4 };
    tlp.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
    tlp.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));
    tlp.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
    tlp.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));
    panel1.Controls.Add(tlp);
    foreach (var item in fields)
    {
        tlp.Controls.Add(new Label() { Text = item, AutoSize = true });
        tlp.Controls.Add(new TextBox() { Dock = DockStyle.Fill });
    }
}