2011-06-05 82 views
2

我正在编写一个关于在picturebox中尝试不同图像的程序,但图像必须与文本相对应。另外它必须来自项目的“资源”文件夹。Picturebox中的图像c#

这就是我想做的事情,如果文本“苹果”出现在屏幕上,然后用一个文件名“苹果”的形象也将在PictureBox中显示..

我可以在“如果 - 做否则”像这样

string word="apple"; 
if(word==apple) 
pictureBox1.Image= WindowsFormsApplication4.Properties.Resources.apple; 

,但如果我有一千个图像,我仍然认为有这个一个简单的方法,..

我想要这个,,

string word=label1.Text;//label1.text changes from time to time 
pictureBox1.Image= WindowsFormsApplication4.Properties.Resources.word; 

但我知道“字”是串....这是不可能的......我不能追加字符串语法....

回答

5

你可以在一个字符串中使用ResourceManager类的GetObject方法传递:

string itemName = label1.Text; 
this.pictureBox1.Image = 
    (Image)Properties.Resources.ResourceManager.GetObject(itemName); 
+0

感谢您的工作!它与冲击波一样吗? – 2011-06-07 14:01:53

+0

@Soliven Shockwave?不知道那是什么。 – 2011-06-07 15:27:18

1

如果打开资源.Designer.cs文件中的代码,你会看到类似这样的:

internal static System.Drawing.Bitmap apple { 
    get { 
     object obj = ResourceManager.GetObject("apple", resourceCulture); 
     return ((System.Drawing.Bitmap)(obj)); 
    } 
} 

这样你就可以做同样的事情:

string word=label1.Text;//label1.text changes from time to time 
pictureBox1.Image= (System.Drawing.Bitmap)WindowsFormsApplication4 
              .Properties 
              .Resources 
              .ResourceManager.GetObject(word);