Question

I have a problem to make a string to name of picture box in C#. I have 256 PictureBoxes in my form.

Now, I have a string array which is RanPicture += "Random" + Pic[step1 + 1]; This one will actually read a series of data from a text file.

What I want is actually to make RanPicture to the name of the PictureBox, so that the pictures will be shown in specified PictureBox from reading a series of string data.

For example, now I have a data is 00 in my text file. And one of the PictureBox is Random00. So here, RanPicture(string) must same as Random00 (name of the PictureBox),then picture will be shown in Random00 through this:

RanPicture.Image = Image.FromFile(Directory.GetCurrentDirectory() + "\\images\\image" + imagePic + ".jpg");

Anyone know how to convert the string to PictureBox name?

Thanks for helps!!!

Was it helpful?

Solution 2

May be this is not the best way, you can use the following function ...

private PictureBox getPictureBoxByName(string name)
{
    foreach(object p in this.Controls ){
        if( p.GetType() == typeof(PictureBox) )
            if( ((PictureBox)p).Name == name )
                return (PictureBox)p;
    }
    return new PictureBox(); //OR return null;
}

The function returns PictureBox object on your form by given the name of string.

And change your code like

getPictureBoxByName(RanPicture).Image = 
Image.FromFile(Directory.GetCurrentDirectory() + 
"\\images\\image" + imagePic + ".jpg");

OTHER TIPS

You can access the controls as an array like this. Then you can easily change the name as you like it.

PictureBox RanPicture = (PictureBox)this.Controls["PictureBox01"];
RanPicture.Image = Image.FromFile(Directory.GetCurrentDirectory() + "\\images\\image" + imagePic + ".jpg");

First get the picture box whose name attribute you need to set

PictureBox a = (PictureBox)this.Controls.Find("pictureBox1", true)[0];
//if you have unique names for your picturebox

Next change the name attribute

a.Name = "newName";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top