Julien Powell
Julien Powell

Reputation: 176

Loading a specific image using the name of a variable handed to a function

So I am wanting to load an image with the use of a function that receives as a string the name of the image it needs to load and then have it load it however I cannot get this to work as I think the program is simply trying to load the variable name rather that the the string it stores(which is the actual name of the image). Sorry if that's badly worded hopefully my code clears up what I mean.

bool FlagDisplay(PictureBox team, string teamName)//Displays the flag of the team that was selected
{
    if (teamName == "Canada")
    {
        team.Image = Properties.Resources.Canada;
    }
    else if (teamName == "New Zealand")
    {
        team.Image = Properties.Resources.NZ;
    }
    else if (teamName == "South Africa")
    {
        team.Image = Properties.Resources.RSA;
    }
    return (true);
}

I want my code to work more like

bool FlagDisplay(PictureBox team, string teamName)//Displays the flag of the team that was selected
{
    team.Image = Properties.Resources.teamName;
}

Upvotes: 1

Views: 2265

Answers (3)

Enigmativity
Enigmativity

Reputation: 117175

I would be inclined to code your FlagDisplay method like this:

bool FlagDisplay(PictureBox team, string teamName)
{
    var images = new Dictionary<string, string>()
    {
        { "Canada", Properties.Resources.Canada },
        { "New Zealand", Properties.Resources.NZ },
        { "South Africa", Properties.Resources.RSA },
    };
    if (images.ContainsKey(teamName))
    {
        team.Image = new Bitmap(images[teamName]);
        return true;
    }
    return false;
}

The advantage with this approach is that you can pull the dictionary out of the method and build it dynamically to handle different countries or image locations without necessarily needing to recompile your FlagDisplay source.

If that causes an error then you don't have full image paths in your resources.

Upvotes: 0

Ron Beyer
Ron Beyer

Reputation: 11273

var imageToShow = Properties.Resources.ResourceManager.GetObject(teamName);

imageToShow will be a System.Drawing.Bitmap.

See https://msdn.microsoft.com/en-us/library/963f81yd(v=vs.110).aspx

Upvotes: 2

Scott Selby
Scott Selby

Reputation: 9580

A PictureBox only contains one Picture. If you want to change the image that it is displaying , then you need to pass an actual Image to it, not just a string.

so , try this:

public void FlagDisplay(PictureBox team, string teamName)//Displays the flag of the team that was selected
{
    // note here you probably need to add .jpg or .png to the teamName
    var imageToShow = new Bitmap(teamName); // this takes filename
    team.Image = (Image) imageToShow;
}

Upvotes: 0

Related Questions