我有一系列由以下方式创建的图片框:
PictureBox[] places = new PictureBox[100];
我需要在表格中填写一些图片框。有没有办法以编程方式填写数组或我需要使用:
places[0] = pictureBox1;
...
答案 0 :(得分:2)
PictureBox[] places = this.Controls.OfType<PictureBox>().ToArray();
这将为您提供控件/表单中定义的每个图片框
this refers to the Form
答案 1 :(得分:1)
在我的第一个示例中,我假设您要按照创建它们的顺序将PictureBox放入数组pictureBox1 = places[0];
等。第二个示例使用Tag分配它们在数组中的顺序property作为索引,这是我通常用来向数组添加控件的方式。
第一种方法
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;
}
}
}
}
答案 2 :(得分:0)
使用for循环:
var places = new PictureBox[100];
for (int i = 0; i < places.Length; i++)
{
places[i] = this.MagicMethodToGetPictureBox();
}