I have a string array "abc"
I put this in a for each loop. I want to retrieve an image from resources using the value in the foreach loop and put it into a picture box.
code below:
char[] stringArr = inputted.ToCharArray();
foreach (char i in stringArr)
{
PictureBox pictureBox = new PictureBox();
object obj = ResourceManager.GetObject(i.ToString());
pictureBox.Image = ((System.Drawing.Bitmap)(obj));
Controls.Add(pictureBox);
}
What do i have to do to get this working?
What i am trying to achieve, is a have pictures, each character in the alphabet represents a different picture, the user inputs a string and clicks a button, the users inputs is taken, formed to the stringArr and i want it to output the relevant images based on the string he inputted
You could do something like:
object obj = ResourceManager.GetObject("MyResourceName", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
To get a resource by name.
With ResourceManager
being something like:
var ResourceManager =
new System.Resources.ResourceManager(
"YourAssembly.Properties.Resources",
typeof(Resources).Assembly);
So in your example you could write:
foreach (char i in stringArr)
{
PictureBox pictureBox = new PictureBox();
object obj = ResourceManager.GetObject(i.ToString(), resourceCulture);
pictureBox.Image = ((System.Drawing.Bitmap)(obj));
}
(You also could omit the resourceCulture
parameter if your image is of no special culture).
I do assume that your code is just an excerpt from a larger example since it makes no sense to me to create a PictureBox
inside a look and not assign it to a form.
Here is a simple method you can use
Add to your code and replace XXXAPPNAMEXXX with the name of you application.
public Bitmap GetImageResourceByName(string name)
{
Bitmap MethodResult = null;
try
{
MethodResult = (Bitmap)XXXAPPNAMEXXX.Properties.Resources.ResourceManager.GetObject(name, XXXAPPNAMEXXX.Properties.Resources.resourceCulture);
}
catch //(Exception ex)
{
//ex.HandleException();
}
return MethodResult;
}
Note: Go into Resources.Designer.cs and make the private attribute resourceCulture public.
I have commented out my error handling (ex.HandleException) as yours may differ.