Luke_Smith_Lukasaurus
Luke_Smith_Lukasaurus

Reputation: 59

load an image from resources in Visual C#, using a string?

If I have some resources, eg card1.png, card2.png, etc, I want to them load them into a picBox, but only load the correct image eg, something like

int cardNum = rn.Next(0,cardMax);
picCard.Image = Properties.Resources."card"+cardNum+".png";

Obviously that doesn't work, but how would I do what I am trying to do (load the correct resource after building the resource name into a string)

Upvotes: 0

Views: 4172

Answers (2)

György Kőszeg
György Kőszeg

Reputation: 18013

Instead of the generated properties in the Resources class use the ResourceManager directly:

string resName = $"card{cardNum}.png"; // Check the correct name in the .resx file. By using the wizards the extension is omitted, for example.
picCard.Image = (Image)Properties.Resources.ResourceManager.GetObject(resName);

Upvotes: 2

user6438653
user6438653

Reputation:

Try using:

var rm = new System.Resources.ResourceManager(((System.Reflection.Assembly)System.Reflection.Assembly.GetExecutingAssembly()).GetName().Name + ".Properties.Resources", ((System.Reflection.Assembly)System.Reflection.Assembly.GetExecutingAssembly()));
Image img = (Bitmap)rm.GetObject("resourcesimagename.jpg");

Upvotes: 0

Related Questions