Reputation: 445
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 ?
Upvotes: 1
Views: 7503
Reputation: 101681
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
.
Upvotes: 0
Reputation: 26209
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]);
Upvotes: 2