Retrieve image resource using string variable in foreach loop

前端 未结 2 1790
悲&欢浪女
悲&欢浪女 2021-01-15 21:13

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.

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-15 21:35

    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.

提交回复
热议问题