Haxor
Haxor

Reputation: 19

adding objects from a windows form into a c# list

I have a lot of windows form components that i need to add to an array. Currently i just have a large amount of adds to a list and this is definitely bad practice.

        panelList.Add(panel1);
        panelList.Add(panel2);
        panelList.Add(panel3);
        panelList.Add(panel4);
        panelList.Add(panel5);
        panelList.Add(panel6);
        panelList.Add(panel7);
        panelList.Add(panel8);
        panelList.Add(panel9);
        panelList.Add(panel10);
        panelList.Add(panel11);
        panelList.Add(panel12);
        panelList.Add(panel13);
        panelList.Add(panel14);
        panelList.Add(panel15);
        panelList.Add(panel16);
        panelList.Add(panel17);
        panelList.Add(panel18);
        panelList.Add(panel19);
        panelList.Add(panel20);
        panelList.Add(panel21);
        panelList.Add(panel22);
        panelList.Add(panel23);
        panelList.Add(panel24);
        panelList.Add(panel25);

        labelList.Add(label1);
        labelList.Add(label2);
        labelList.Add(label3);
        labelList.Add(label4);
        labelList.Add(label5);      
        labelList.Add(label6);
        
        labelList.Add(label7);
        labelList.Add(label8);
        labelList.Add(label9);
        labelList.Add(label10);
        labelList.Add(label11);
        labelList.Add(label12);
        labelList.Add(label13);
        labelList.Add(label14);
        labelList.Add(label15);
        labelList.Add(label16);
        labelList.Add(label17);
        labelList.Add(label18);
        labelList.Add(label19);
        labelList.Add(label20);
        labelList.Add(label21);
        labelList.Add(label22);
        labelList.Add(label23);
        labelList.Add(label24);
        labelList.Add(label26);

is there a way in c# to add these elements in a for loop etc. Thanks.

Upvotes: 1

Views: 180

Answers (1)

dimitar.bogdanov
dimitar.bogdanov

Reputation: 394

You can put all of the labels, panels, etc. in their own encapsulating panel. This will make them children of the panel, and you can iterate over them easily:

foreach (Control ctrl in panelContainer.Controls) // panelContainer is a Panel
{
    labelList.Add((Label) ctrl);
}

I strongly recommend not to do that. It's kind of messy in the designer (if you're using that), adds more uncecessary controls to worry about, and if you accidentally add something that isn't a label, your app will crash.

A simpler way to do it is by using the method from this answer on a similar question. You can apply it as such:

panelList.AddRange(this.FindChildControlsOfType<Panel>());
labelList.AddRange(this.FindChildControlsOfType<Label>());

If you insist on iterating, that's obviously doable as well:

foreach (Label label in this.FindChildControlsOfType<Label>())
{
    labelList.Add(label);
}

Upvotes: 1

Related Questions