[英]Add pictureBox to List
In my winform app I have 3 pictureBox, and I want to add them to a List. 在我的winform应用程序中,我有3个pictureBox,我想将它们添加到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' " “无法将类型'System.Windows.Forms.Control []'转换为'System.Windows.Forms.PictureBox'”
Can anyone help ? 有人可以帮忙吗?
Problem : Controls.Find()
method returns the Control[]
Array 问题: Controls.Find()
方法返回Control[]
数组
Solution : You need to Access the First Element of the Controls Array to cast it backto PictureBox
. 解决方案:您需要访问Controls数组的第一个元素以将其强制转换回PictureBox
。
Replace This: 替换这个:
pictureBoxList.Add((PictureBox)Controls.Find("pictureBox" +i, true));
With This: 有了这个:
pictureBoxList.Add((PictureBox)Controls.Find("pictureBox" +i, true)[0]);
You can use LINQ
for that: 您可以使用LINQ
:
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
. 你的问题是Controls.Find
方法返回一个控件数组,你试图将控件数组转换为Picturebox
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.