开发者

C# Form Controls

I have a form contain开发者_Go百科ing 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>;


Can you use the ControlCollection.Find( ) method on the forms Controls property?


if you only have the name of the picture controls and not a reference to them ( which I think you could have kept in a dictionary with name and reference when you created those controls earlier in the form... ), the only way you have I think is to search in the Form.Controls collection until you find the one with the name you are looking for and which is of the picture box type.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜