【问题标题】:Filling an array with pictureboxes用图片框填充数组
【发布时间】:2023-04-05 10:10:02
【问题描述】:

我有一组由以下人员创建的图片框:

PictureBox[] places = new PictureBox[100];

我需要用表单中的一些图片框来填写它。有没有办法以编程方式填写数组或者我需要使用:

places[0] = pictureBox1;
...

【问题讨论】:

  • 我在 Visual Studio 2013 中使用 C# 和可视化表单编辑器。

标签: c# arrays


【解决方案1】:
PictureBox[] places = this.Controls.OfType<PictureBox>().ToArray();

这将为您获取控件/表单中定义的每个图片框

this refers to the Form

【讨论】:

  • 有什么办法不选择某些图片框?
  • 是的,只需在表达式上放一个 where 子句
【解决方案2】:

在我的第一个示例中,假设您希望按照创建图片框的顺序将它们放入数组中 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;
            }
        }
    }
 }

【讨论】:

    【解决方案3】:

    使用 for 循环:

    var places = new PictureBox[100];
    for (int i = 0; i < places.Length; i++)
    {
      places[i] = this.MagicMethodToGetPictureBox();
    }
    

    【讨论】:

    • 你如何让MagicMethodToGetPictureBox按顺序返回图片框?他已经有表格上的图片框了。
    • 我想我误解了 OP 的问题;我以为他想知道如何初始化数组……抱歉!
    猜你喜欢
    • 1970-01-01
    • 2022-01-16
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    相关资源
    最近更新 更多