用图片框填充数组

本文关键字:填充 数组 | 更新日期: 2023-09-27 18:25:48

我有一组图片框,由创建

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();
}