Reputation: 199
I wonder if there is any way to write the following code a lot shorter...
public PictureBox pb1;
public PictureBox pb2;
public PictureBox pb3;
.....
public PictureBox pb50;
And then, is there any way to add all those variables to a list, without having to perform the same ugly code again.
listPB.add(pb1); listPB.add(pb2);...... ListPB.add(pb50);
The method I use is really dumb and I hoped that there were some other way to do it. Thanks for the help!
Upvotes: 6
Views: 8271
Reputation: 95
you can do this :
List<PictureBox> listPicture = new List<PictureBox>() { pb1, pb2, pb3, pb4, pb5, etc... };
Upvotes: 2
Reputation: 20658
If the list is yours to initialize, I would use array in the beginning:
PictureBox[] pictures = new PictureBox[50];
for (int i = 0; i < pictures.Length; i++)
{
pictures[i] = new PictureBox();
// Do something else
}
If the 50 instances are generated through another way, I suggest using Notepad++ Find and Replace
with Regex.
Upvotes: 1
Reputation: 26312
List<PictureBox> list = new List<PictureBox>();
for(int i = 0; i < 50; i++)
{
list.add(new PictureBox{
//set properties here..
});
}
Upvotes: 1
Reputation: 58
Use this:
public PictureBox pb1,pb2,pb3,pb4....,pb50;
then
List<PictureBox> listPB = new List<PictureBox>{pb1, pb2, ..., pb50};
Upvotes: 2
Reputation: 934
Use a loop
for(int i = 0; i < 10; i++)
{
PictureBox p = new PictureBox();
listPb.Add(p);
}
Upvotes: 2
Reputation: 30882
You can make an ad-hoc collection like this:
PictureBox[] pictureBoxen = {pb1, pb2, pb3, ..., pb50};
and then you can use AddRange
on the list to add them
listPB.AddRange(pictureBoxen);
Or if listPB
is created on that place, and only contains those variables, you could do:
List<PictureBox> listPB = new List<PictureBox>{pb1, pb2, ..., pb50};
Note that this kind of syntax was only introduced in C#3, in 2008, so it is safe to assume that you are using that or higher.
For C#2 and below, looping is the best I could come up with.
Upvotes: 8