Search code examples
c#winformsresourcespicturebox

Accessing an image resource by name and assigning it to a PictureBox


I have this list:

List<string> list = new List<string>();
list.Add("dog.jpg");
list.Add("cat.jpg");
list.Add("horse.jpg");

In my resources, I have 3 images named: dog, cat, and horse. I want to display them in a picture box using the list.

I have tried something like this:

pictureBox1.Image = project.Properties.Resources.list[2]; // should display the horse image

The problem is that it displays the error:

'Resources' does not contain a definition for 'list' `

How can I get the image using the name in the list?


Solution

  • Properties.Resources only knows the resources (dog, cat, and horse) so you can't give him a string and expect him to know the resource. You need to use the GetObject method from the ResourceManager like this:

    (Bitmap)Properties.Resources.ResourceManager.GetObject(list[2])
    

    This should give you the horse image.