Search code examples
c#imagewinformsfor-loopembedded-resource

Select an Image from Resources on user input to set the Image of a PictureBox


This probably doesn't make a lot of sense, but I'm trying to change the image of a PictureBox to a users request if a user has searched for it and it matches one in a current string.

I keep receiving a "System.ArgumentException: 'Parameter is not valid.'" when I run it.

Each string in the array matches the name of an Image in the Project's Resources.

string[] TShirts = new string[] { "New York", "Melbourne", "London", "Sydney", "Los Angeles" };

for (int i = 0; i < TShirts.Length; i++ )
{
    if (txtSearch.Text == TShirts[i])
    {
        string x = TShirts[i];
       ptbItem.Image = new Bitmap(x); // error occurs here (this is what I can't work out)
    }
} 

Solution

  • You can use the ResourceManager to access resources by name at run-time.
    You can pass a string to its GetObject() method and cast to the resource Type.

    For example:

    int idx = Array.IndexOf(TShirts, txtSearch.Text);
    
    if (idx >= 0) {
        ptbItem.Image?.Dispose();
        ptbItem.Image = (Bitmap)Properties.Resources.ResourceManager.GetObject(TShirts[idx]);
    }
    

    Since you have a collection of strings, you could fill a ComboBox instead of using a TextBox as input, so your Users don't need to guess a name and avoid type mistakes.