Martin Kiper
Martin Kiper

Reputation: 5

C# Add image to pictureboxes with List

First of all, sorry for my english.

I'm making a program that has about 60 pictureboxes. (pictureBox1, pictureBox2, pictureBox3, till pictureBox60)

And I have a list with 60 strings. (urls to different images)

I want for pictureBox1 to load the list[0], pictureBox2 to load the list[1], etc..

But i realized i can't make the following:

for (int i = 0; i < Bans.Count; i++)
{
    this.pictureBox + i = this.Bans[i]; //Can't be done.. 
}

Is there a solution that does not require me to manually set all 60 boxes?

Thanks!

Upvotes: 0

Views: 491

Answers (1)

Dai
Dai

Reputation: 155055

If this is WinForms, you can use ControlCollection.Find to get controls by name - assuming each of your pictureboxN controls has a matching .Name property value.

e.g.

pictureBox23.Name = "pictureBox23";

like so:

for( int i = 0; i < this.Bans.Count; i++ ) {

    String pictureBoxName = "pictureBox" + i.ToString(CultureInfo.InvariantCulture);
    Control[] matchingPictureBoxes = this.Controls.Find( pictureBoxName, searchAllChildren: true );
    if( matchingPictureBoxes.Length == 1 ) {
        PictureBox pictureBox = (PictureBox)controls[0];
        pictureBox.Image = this.Bans[i];
    }
}

Upvotes: 1

Related Questions