locked
Use a varaible value in a line of code RRS feed

  • Question

  • I'm creating a game involving dice and want to display the correct dice as an image based on a random number 1-6. I have my images named "dice1", "dice2", .. "dice6" and have them stored in the resources file. I want to write a single line of code to display "diceX" where X is the value of the random integer. For example:

    int x = rand.Next(1, 7);
    pictureBox1.Image = Properties.Resources.**dicex**;

    So if x = 2 then it would be the equivilant of "pictureBox1.Image = Properties.Resources.dice2;"

    I could obviously do this using a switch statement with 6 separate cases, but I will be this in several places and it seems like there should be a better way.

    Tuesday, August 7, 2012 2:32 AM

Answers

  • U should use ResourceManager,then u can do something like this(Suppose ur proj's namespace is WinFormCSharp, and your Resource file is in the "Resource" folder)——

    ResourceManager rm = new ResourceManager("WinFormCSharp.Resources.Resources",Assembly.GetExecutingAssembly());
    BackgroundImage = (Bitmap)rm.GetObject("Desert");
    I mean that u can dynamically change the ResourceManager's constructor string according to the condition.

    下载MSDN桌面工具(Vista,Win7)
    我的博客园
    慈善点击,点击此处

    • Marked as answer by peetahz Tuesday, August 7, 2012 3:42 AM
    Tuesday, August 7, 2012 3:18 AM

All replies

  • U should use ResourceManager,then u can do something like this(Suppose ur proj's namespace is WinFormCSharp, and your Resource file is in the "Resource" folder)——

    ResourceManager rm = new ResourceManager("WinFormCSharp.Resources.Resources",Assembly.GetExecutingAssembly());
    BackgroundImage = (Bitmap)rm.GetObject("Desert");
    I mean that u can dynamically change the ResourceManager's constructor string according to the condition.

    下载MSDN桌面工具(Vista,Win7)
    我的博客园
    慈善点击,点击此处

    • Marked as answer by peetahz Tuesday, August 7, 2012 3:42 AM
    Tuesday, August 7, 2012 3:18 AM
  • Slightly different than what I was thinking of, but that works wonderfully.

    Thanks!

    Tuesday, August 7, 2012 3:42 AM