C#创建图片盒阵列的更简单方法(48x盒子)

时间:2015-04-17 11:10:59

标签: c# arrays string picturebox

项目环境:Visual Studio 2013,使用Windows窗体模板。

这就是我目前所拥有的,我假设有一种更简单的方法来创建这样的数组。我尝试了很多方法,但我还不太了解C#。

   PictureBox[] boxes = {
                 runeBox1, runeBox2, runeBox3, runeBox4, runeBox5, runeBox6, runeBox7, runeBox8, 
                 runeBox9, runeBox10, runeBox11, runeBox12, runeBox13, runeBox14, runeBox15, runeBox16, 
                 runeBox17, runeBox18, runeBox19, runeBox20, runeBox21, runeBox22, runeBox23, runeBox24, 
                 runeBox25, runeBox26, runeBox27, runeBox28, runeBox29, runeBox30, runeBox31, runeBox32, 
                 runeBox33, runeBox34, runeBox35, runeBox36, runeBox37, runeBox38, runeBox39, runeBox40, 
                 runeBox41, runeBox42, runeBox43, runeBox44, runeBox45, runeBox46, runeBox47, runeBox48};

到目前为止我所尝试的是:

string[] strArr = new string[48];
        for (int i = 1; i != 48; i++)
            {
            strArr[i] = "runebox" + i.ToString();
            }
        int count = 0;
        foreach (object p in this.Controls)
            {
            if (p.GetType() == typeof(PictureBox))
                {
                if (((PictureBox)p).Name == strArr[count])
                    {
                    boxes[count] = ((PictureBox)p);
                    count++;
                    }
                }
            }

这是编译,但它在数组框中给出了一个nullpointer异常。

我也尝试过一个转换器,但这也没有给我带来任何结果。

希望你们中的一些聪明人能告诉我通往罗马的道路。

2 个答案:

答案 0 :(得分:0)

可以在一个句子中找到表格上的所有图片框

private PictureBox[] boxes;
.ctor
{
    InitializeComponent();
    boxes = this.Controls.OfType<PictureBox>()
            .Where(pb => pb.Name.StartsWith("runeBox"))
            .OrderBy(pb => int.Parse(pb.Name.Replace("runeBox","")))
            .ToArray();
}

答案 1 :(得分:0)

如果你只是想创建它,然后手动将它们添加到表单中,你可以使用LINQ和Enumerables

你可以像这样创建它们:

var pictureboxes = Enumerable.Range(1,48).ToList().Select(i=> new PictureBox(){Name = "runebox" + i.ToString()}).ToList();

然后添加到表单中即可:

pictureboxes.ForEach(pic=> this.Controls.Add(pic));