如何将图片框放在图片框数组中

本文关键字:数组 | 更新日期: 2023-09-27 18:35:38

我只想将我的图片框保存在数组中以便以后处理它们,我做了一个解决方案来获取这些图片框,但它太大了,我很确定有一种方法可以更轻松地做到这一点,这就是我想要的

public PictureBox[] getboxes()
        {
            PictureBox[] boxes = new PictureBox[]{pictureBox1,pictureBox2,pictureBox3,pictureBox4,pictureBox5,pictureBox6,pictureBox7,pictureBox8,pictureBox9,pictureBox10,pictureBox20,pictureBox19,pictureBox18,pictureBox17,pictureBox16,pictureBox15,pictureBox14,pictureBox13,pictureBox12,pictureBox11,
            pictureBox40,pictureBox39,pictureBox38,pictureBox37,pictureBox36,pictureBox35,pictureBox34,pictureBox33,pictureBox32,pictureBox31,pictureBox30,pictureBox29,pictureBox28,pictureBox27,pictureBox26,pictureBox25,pictureBox24,pictureBox23,pictureBox22,pictureBox21,
            pictureBox60,pictureBox59,pictureBox58,pictureBox57,pictureBox56,pictureBox55,pictureBox54,pictureBox53,pictureBox52,pictureBox51,pictureBox70,pictureBox69,pictureBox68,pictureBox67,pictureBox66,pictureBox65,pictureBox64,pictureBox63,pictureBox62,pictureBox61,
            pictureBox80,pictureBox79,pictureBox78,pictureBox77,pictureBox76,pictureBox75,pictureBox74,pictureBox73,pictureBox72,pictureBox71,pictureBox50,pictureBox49,pictureBox48,pictureBox47,pictureBox46,pictureBox45,pictureBox44,pictureBox43,pictureBox42,pictureBox41,
            pictureBox90,pictureBox89,pictureBox88,pictureBox87,pictureBox86,pictureBox85,pictureBox84,pictureBox83,pictureBox82,pictureBox81,pictureBox100,pictureBox99,pictureBox98,pictureBox97,pictureBox96,pictureBox95,pictureBox94,pictureBox93,pictureBox92,pictureBox91};
            return boxes;
        }

如您所见,这太大了

请帮助使这更容易吗?

如何将图片框放在图片框数组中

每个 .Net 控件都有一个属性 Controls,它允许访问其子控件。

因此,如果您所有的图片框都在同一个容器中,假设一个面板"panel1",以检索您可以使用的每个图片框:

foreach(var ctl in panel1.Controls)
{
   var box = ctl as PictureBox;
   if(box != null)
   {
       // Do what you want : add to an array, get the picture...
   }
}

要用所有图片框填充数组:

List<PictureBox> pboxes = new List<PictureBox>();
foreach(var ctl in panel1.Controls)
{
   var box = ctl as PictureBox;
   if(box != null)
   {
       pboxes.Add(box);
   }
}
// pboxes now contains all PB. You can call "AsArray()" LINQ method on it to get an array rather than a List.