简体   繁体   中英

C# Form Controls

I have a form containing many picture boxes named pb_a1,pb_a2,pb_a3... and so on..

I have a String array containing the picture box names. 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.

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. Do that during form creation (after InitializeComponent).

Next time you have to access a picture box by its name, just use:

myDictionary["pictureboxname"].Image = blabla;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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