0

I'm trying to dynamically add some controls (currently text boxes and labels) to a form. There isn't a set number of pairs to be drawn`.

Example of what I'm trying to achieve.

As you can see, the table runs out of space, so it moves over to the right.

Currently, I am using a TableLayoutPanel within a FlowLayoutPanel.
Column 0 contains the label and column 1 contains the textbox.

How do I, or rather, can I get the FlowLayoutPanel to split the 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);
    }
1
  • Use a control designed for dynamically adding fields, like DataGridView, not a TableLayoutPanel. Commented Oct 9, 2017 at 22:49

1 Answer 1

3

You can use TableLayoutPanel having 4 columns, and set suitable ColumnStyles for the control.

Example

Put a button and a panel on the form and set anchors of panel to all edges. Then handle click event of the button and use this code:

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 });
    }
}

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.