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?
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.
When you add images, strings, etc. to a resource file (.resx), Visual Studio automatically generates strongly-typed properties in the corresponding Resources class for you. So for example, if you added horse.jpg to Resources.resx in your project, there should be a horse property on the Properties.Resources class which returns a System.Drawing.Bitmap. So you should be able to do:
pictureBox1.Image = Properties.Resources.horse;
If you want to be able to access an image resource by name, then you can do it the same way the generated code does it, using ResourceManager.GetObject. But note the image resource name will not include the .jpg extension and you will have to cast the result to a Bitmap:
pictureBox1.Image = (Bitmap)Properties.Resources.ResourceManager.GetObject("horse");
You could create a helper method which will strip the extension off the filename and retrieve the resource, like this:
private Bitmap GetImageResource(string filename)
{
string resourceName = filename.Substring(0, filename.IndexOf("."));
return (Bitmap)Properties.Resources.ResourceManager.GetObject(resourceName);
}
That would allow you to use it with your list like this:
pictureBox1.Image = GetImageResource(list[2]);
Try calling pictureBox1.Refresh(); after assigning the image.
来源:https://stackoverflow.com/questions/47592576/accessing-an-image-resource-by-name-and-assigning-it-to-a-picturebox