user841123
user841123

Reputation:

Adding array of control dynamically to the winform

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

Upvotes: 5

Views: 7738

Answers (2)

Beatles1692
Beatles1692

Reputation: 5320

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

Upvotes: 1

Cody Gray
Cody Gray

Reputation: 244712

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.

Upvotes: 15

Related Questions