5

I have a question, I want to add an array of control to the windows form dynamically, I have prepared the code like following, but the question is only the first controls shows in the form remaining are present in controls collection but not shown on form. What is missing in the code?

Code:

LinkLabel[] arrLbl = new LinkLabel[5];

for (int i = 0; i < 5; i++)
{
   LinkLabel lbl = new LinkLabel();
   lbl.Text = "Label: " + i.ToString();
   arrLbl[i] = lbl;
}

foreach (Control c in arrLbl)
  this.Controls.Add(c);

2 Answers 2

15

Your code is correct. The problem is most likely that all of the controls you're adding are just stacking on top of one another, causing you to only see the one that is on top.

I don't know what type of container control you're adding them to, but consider adding them to a FlowLayoutPanel, which will handle automatically arranging its child controls.

You can choose whether you want the child controls to "flow" vertically or horizontally by setting the FlowDirection property.

If you don't want to use a FlowLayoutPanel (or other intelligent container control), then you'll have to manually set the Location property of each of your child controls.

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

Comments

1

You should set the Location property of each control .They are all being rendered on each other.

3 Comments

Should I do something like this: lbl[index].Location = new Point(x, y). Have tried it before but not worked for me! what would be the reason?
X was static and y was incriminated through loop like this: lbl.Location = new Point(0, counter+10);
Will you please take a look at the code I have asked the question here

Your Answer

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