rathi bond
rathi bond

Reputation: 81

Changing the picture in a pictureBox with a variable

This is my code to load a picture box with an image and it works fine.

picBox1.Image = Properties.Resources.imageName;

I would like to replace "imageName" with a variable like String x = "imageName" and change the code to something like this.

picBox1.Image = Properties.Resources.x;

It does not seem to work. Is there some other way to do it, and why does this not work? Thank you. Also, noob alert. I did google the question and look around for a solution before asking on these forums.

Upvotes: 2

Views: 3527

Answers (2)

Zoltan Tirinda
Zoltan Tirinda

Reputation: 799

This should solve your problem

using System.Drawing;
using System.Resources;

...

ResourceManager resManager = new ResourceManager("YourRootNamespace.YourResourceFileName", GetType().Assembly);
Image myImage = (Image)(resManager.GetObject("ImageNameInResourceFile"));
picBox1.Image = myImage;

Upvotes: 0

marsouf
marsouf

Reputation: 1147

// given that x is a string variable referring to a resource name
// you can do the following
picBox1.Image = (Image)Properties.Resources.ResourceManager.GetObject(x);

Upvotes: 2

Related Questions