Picturebox中的图像c#

时间:2011-06-05 01:58:22

标签: c# image picturebox

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

这是我想要做的,如果文本“apple”显示在屏幕上,那么带有文件名“apple”的图像也会显示在图片框中。

我可以在“if-else”这样做

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;

但我知道“word”是字符串....这是不可能的...我不能在语法中附加字符串......

2 个答案:

答案 0 :(得分:5)

您可以使用ResourceManager类的GetObject方法传入字符串:

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

答案 1 :(得分: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);