Load image from resources

a1204773 picture a1204773 · Nov 27, 2012 · Viewed 137.9k times · Source

I want to load the image like this:

void info(string channel)
{
    //Something like that
    channelPic.Image = Properties.Resources.+channel
}

Because I don't want to do

void info(string channel)
{
    switch(channel)
    {
        case "chan1":
            channelPic.Image = Properties.Resources.chan1;
            break;
        case "chan2":
            channelPic.Image = Properties.Resources.chan2;
            break;
    }
}

Is something like this possible?

Answer

Picrofo Software picture Picrofo Software · Nov 27, 2012

You can always use System.Resources.ResourceManager which returns the cached ResourceManager used by this class. Since chan1 and chan2 represent two different images, you may use System.Resources.ResourceManager.GetObject(string name) which returns an object matching your input with the project resources

Example

object O = Resources.ResourceManager.GetObject("chan1"); //Return an object from the image chan1.png in the project
channelPic.Image = (Image)O; //Set the Image property of channelPic to the returned object as Image

Notice: Resources.ResourceManager.GetObject(string name) may return null if the string specified was not found in the project resources.

Thanks,
I hope you find this helpful :)