Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Changing a picturebox image to users search from a textbox

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.

string[] TShirts = new string[] { "New York", "Melbourne", "London", "Sydney", "Los Angeles" };
// each value in the array has the same name as the images in the resources

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)
    }
} 

I’m really sorry for my poor explaining, I hope you can understand what I mean.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading