benf
benf

Reputation: 77

C# Use string as a resource name

I'm creating a card game similar to Play Your Cards Right using C# WFA.

I have 52 card faces as PNGs that I want to be able to apply to pictureboxes. I have 10 picture boxes, pbP1Card1 -> pbP1Card5 and pbP2Card1 -> pbP2Card5. When a card is drawn, I want to change the next picturebox from a cardback image to the corresponding card face for the newly drawn card.

I am trying to find a fast solution to getting this to work across all ten PBs. I am thinking of a method similar to this:

string picbox = "pbP1Card1"; 
string card = "ace_of_spades"; 

is used in

picbox.Image = Properties.Resources.card

Where the picbox being targeted and the current card can be changed accordingly.

EDIT:
Along with Joe's answer, I have achieved what I wanted by using the following:

picbox.Image = ((System.Drawing.Image)(Properties.Resources.ResourceManager.GetObject(card)));

Upvotes: 1

Views: 781

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415600

string picbox = "pbP1Card1"; 
picbox.Image = Properties.Resources.card

That's not gonna work at all the way you want. Using string values as variable name references is not good practice. Instead, define your PictureBox controls with an array, like this:

PictureBox[,] cards = new PictureBox[1,4];

Now, pbP1Card1 will be cards[0,0]. pbP2Card5 would be cards[1,4], and you can use integer variables to increment through the positions. So you might have a line of code somewhere that looks like this:

cards[0,i].Image = Properties.Resources.card

The best thing here is you don't have to remove and recreate your existing PictureBoxes. Instead, your initialization code has a few lines that look like this:

 cards[0,0] = pbP1Card1;
 cards[0,1] = pbP1Card2;
 cards[0,2] = pbP1Card3;
 //...
 cards[1,4] = pbP2Card4;

Since PictureBox is a reference type, you will be able to access the same PictureBox object using either reference, so anything you've already written to use the existing names will still work.

Upvotes: 4

Related Questions