Question

In my winform app I have 3 pictureBox, and I want to add them to a List.
I tried

List<PictureBox> pictureBoxList = new List<PictureBox>();  

for (int i = 0; i < 3; i++)  
{ 
 pictureBoxList.Add((PictureBox)Controls.Find("pictureBox" +i, true)); 
}

I get the error

"Cannot convert type 'System.Windows.Forms.Control[]' to 'System.Windows.Forms.PictureBox' "

Can anyone help ?

Was it helpful?

Solution

Problem : Controls.Find() method returns the Control[] Array

Solution : You need to Access the First Element of the Controls Array to cast it backto PictureBox.

Replace This:

pictureBoxList.Add((PictureBox)Controls.Find("pictureBox" +i, true));

With This:

pictureBoxList.Add((PictureBox)Controls.Find("pictureBox" +i, true)[0]);

OTHER TIPS

You can use LINQ for that:

var pictureBoxList = this.Controls.OfType<PictureBox>()
            .Where(x => x.Name.StartsWith("pictureBox"))
            .ToList(); 

Your problem is Controls.Find method returns an array of controls and you are trying to cast a control array to Picturebox.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top