1

I need to create an array of label and text boxes dynamically.

I have a groupBox and I need to add the above to it. What is the best way to align then correctly? How do you get the location?

below does not work

    public void TestCreateInputLabelAndTextBox()
    {

        foreach (Parameter parameter in Params)
        {
            var lbl = new Label();
            lbl.Name = "lbl" + parameter.Name;
            lbl.Text = parameter.Name;
            lbl.AutoSize = true;
            lbl.Location = new Point(7, 30);
            lbl.Name = "label1";
            lbl.Size = new Size(35, 13);


            var txtBox = new TextBox();
            txtBox.Name = "txt" + parameter.Name;
            txtBox.Text = parameter.Name;
            txtBox.Location = new Point(20, 20);
            txtBox.Location = new Point(49, 22);
            txtBox.Size = new Size(100, 20);


            groupBox1.Controls.Add(lbl);
            groupBox1.Controls.Add(txtBox);
        }

    }

How do you do it?

5
  • 1
    How would you calculate their locations with pen-and-paper? Try that first, then take your logic and convert it to code. Commented Jun 22, 2012 at 13:45
  • 1
    Consider ditching the labels and textboxes and use a datagridview instead. Then all you need to do is add rows. Commented Jun 22, 2012 at 13:48
  • 1
    Use standard containers like FlowLayoutPanel, TableLayoutPanel, etc for aligning purpose. Commented Jun 22, 2012 at 13:51
  • 1
    If they're all going to be the same size, you can have them located at fixed intervals. You'll need a starting location and then add to that for each new textbox and label. Commented Jun 22, 2012 at 13:56
  • The reason you're getting random suggestions is that we don't understand what problem you're trying to solve. Why do you need to do this? What "does not work" about what you are doing? Commented Jun 22, 2012 at 20:18

2 Answers 2

3

you must make an array of textbox and lable for example:

TextBox[] txt= new TextBox[10];
for (int i = 0; i <=10; i++) {
    txt(i) = new TextBox();
    txt(i).Text = i.Tostring();
    if (i > 0) {
        txt(i).Left = txt(i - 1).Right;
    }

    this.Controls.Add(txt(i));
}
Sign up to request clarification or add additional context in comments.

Comments

0

Further to comments placed above I have used a tablePanelLayout.

I am sorry that my question seems not to have been clear. I tried to be as concise as possible because I beleive that the more you say the more you can confuse somebody who might help you.

All I needed was some pointers.By using a tablePanellayout solved my problem. thanks for your 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.