我有一组由以下人员创建的图片框:
PictureBox[] places = new PictureBox[100];
我需要在表格中填写一些图片框。有没有办法以编程方式填写数组或者我需要使用:
places[0] = pictureBox1;
...
PictureBox[] places = this.Controls.OfType<PictureBox>().ToArray();
这将为您提供控件/表单中定义的每个图片框
this refers to the Form
在我的第一个示例中,假设您希望按照创建 PictureBoxes 的顺序将它们放入数组中pictureBox1 = places[0];
。第二个示例通过使用 Tag 属性作为索引来分配它们在数组中的放置顺序,这是我通常用来向数组添加控件的方式。
第一种方法
private void button1_Click(object sender, EventArgs e)
{
var places = new PictureBox[10]; // I used 10 as a test
for (int i = 0; i < places.Length; i++)
{
// This does the work, it searches through the Control Collection to find
// a PictureBox of the requested name. It is fragile in the fact the the
// naming has to be exact.
try
{
places[i] = (PictureBox)Controls.Find("pictureBox" + (i + 1).ToString(), true)[0];
}
catch (IndexOutOfRangeException)
{
MessageBox.Show("pictureBox" + (i + 1).ToString() + " does not exist!");
}
}
}
第二种方法
private void button2_Click(object sender, EventArgs e)
{
// This example is using the Tag property as an index
// keep in mind that the index will be one less than your
// total number of Pictureboxes also make sure that your
// array is sized correctly.
var places = new PictureBox[100];
int index;
foreach (var item in Controls )
{
if (item is PictureBox)
{
PictureBox pb = (PictureBox)item;
if (int.TryParse(pb.Tag.ToString(), out index))
{
places[index] = pb;
}
}
}
}
使用 for 循环:
var places = new PictureBox[100];
for (int i = 0; i < places.Length; i++)
{
places[i] = this.MagicMethodToGetPictureBox();
}