I have an array which holds survey results. I am wanting to put the survey results onto a windows form and place the question in a label and the corresponding answer in a text box. I am housing my questions in a List<string> array and my answers in a List<string> array as well. I have created a tablelayoutpanel on my form and I want to be able to iterate my array and create a label with the question and a text box with the answer beside it. I can't seem to get the formatting set-up properly. This is what I was using.

TextBox tbox = new TextBox();
Label labell = new Label();
labell.Name = "label";
labell.Text = "Test";
tableLayoutPanelAttempt1.Controls.Add(labell,0,1);
tbox.Name = "TextBox";
tbox.Text = "TextBox";
tableLayoutPanelAttemp1.Controls.Add(tbox,0,1);

Recommended Answers

All 3 Replies

I guess tableLayoutPanelAttempt1 is your form.
I don't see you adding label1.
To add the control to the form use:
tableLayoutPanelAttempt1.Controls.Add(MyTblLayoutPanel);
To label1 in the first cell of your TableLayoutpanel use
MyTblLayoutPanel.Add(label1,0,0);

Container.Controls.Add(Control Value)--->Adds the specified value to the control collection of the container. But there are no options to pass arguments for Left and Top position of that control to determine its position.

MyTblLayoutPanel.Add(label1,0,0);---> should be performed an exception or pointed to an error about passing arguments i.e. No overloaded for method 'Add' takes 3 arguments.

The method should be MyTblLayoutPanel.Add(label1);. It automatically adds the control at the position 0,0. So, you would be changed the Location of the control by assigning the values to Left and Top properties of the control.Everytime calculate and assign the Left and Top position property value, when you are trying to add a new control otherwise all are added at the same position and overlaped each other.

Sorry Shark_1 and others... I was a bit confused between the Controls collection of the form and the Controls collection of the TableLayoutPanel.
This will work:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            // made tableLayoutPanel1 in designer so is already 
            // in the Controls collection  of the form 
            // colored background here
            tableLayoutPanel1.BackColor = Color.LawnGreen;

            TextBox tbox = new TextBox();
            tbox.Name = "TextBox";
            tbox.Text = "TextBox";

            Label labell = new Label();
            labell.Name = "label";
            labell.Text = "Test";

            //Add to Controls collection of tableLayoutPanel1
            tableLayoutPanel1.Controls.Add(labell, 0, 0);
            tableLayoutPanel1.Controls.Add(tbox, 0, 1);
        }
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.