简体   繁体   English

C#表单控件

[英]C# Form Controls

I have a form containing many picture boxes named pb_a1,pb_a2,pb_a3... and so on.. 我有一个包含许多名为pb_a1,pb_a2,pb_a3 ...等图片框的表单。

I have a String array containing the picture box names. 我有一个包含图片框名称的String数组。 What I need to do is access each of these and specify an image for it. 我需要做的是访问其中的每一个并为其指定图像。 Instead of hard coding, I would like to know if there is any way by which I can write a loop which gives me commands like 而不是硬编码,我想知道是否有任何方法可以编写一个循环,它给我命令

 > Form1.pb_a1.Image=<some Image>; > > Form1.pb_a2.Image=<some Image>; > > Form1.pb_a3.Image=<some Image>; > > Form1.pb_a4.Image=<some Image>; 

你可以在窗体Controls属性上使用ControlCollection.Find()方法吗?

如果您只有图片控件的名称而不是对它们的引用(我认为您可以在表单中先前创建这些控件时将其保存在带有名称和引用的字典中...),这是您拥有的唯一方法我想是在Form.Controls集合中搜索,直到找到具有您正在寻找的名称的那个,以及哪个是图片框类型。

You're better off storing the picture boxes in a picture box array, rather than a string array. 最好将图片框存储在图片框数组中,而不是字符串数组。

PictureBox[] myPictures = {pictureBox1, pictureBox2, pictureBox3, pictureBox4};

foreach (PictureBox picture in myPictures)
{
    picture.Image = <some Image>;
}

If you have to have it as a string, the following code may help you out. 如果您必须将其作为字符串,以下代码可能会帮助您。 Please note that I haven't included any error checking incase the element doesn't exist. 请注意,我没有包含任何错误检查,因为该元素不存在。 You're likely to just get an empty element in that part of the array. 你可能只是在数组的那一部分得到一个空元素。 You may want to encase it in try/catch as well. 您也可以将其包含在try / catch中。

string[] myPicturesString = {"pictureBox1", "pictureBox2", "pictureBox3", "pictureBox4"};
            PictureBox[] myPictures = new PictureBox[myPicturesString.Length];

            for (int i = 0; i < myPictures.Length; i++)
            {
                foreach (Control c in this.Controls)
                {
                    if (c.Name == myPicturesString[i])
                    {
                        myPictures[i] = (PictureBox) c;
                    }
                }
            }

            MessageBox.Show(myPictures[1].Name);

Assuming that these picturebox are fields of your form, you can reflect (System.Reflection) on the form class, retrieve a reference to the picturebox fields and store them into a dictionary. 假设这些图片框是表单的字段,您可以在表单类上反映(System.Reflection),检索对图片框字段的引用并将它们存储到字典中。 Do that during form creation (after InitializeComponent). 在表单创建期间(在InitializeComponent之后)执行此操作。

Next time you have to access a picture box by its name, just use: 下次您必须按名称访问图片框时,只需使用:

myDictionary["pictureboxname"].Image = blabla;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM