Search code examples
vb.netvisual-studioresourcespictureboxfilepath

Visual studio image loading in for cycle from resources


In my image resources I have pictures with following names: c1.png, c2.png, c3.png, ... Whereas referring to the first image works with My.Resources.c1

I would like to display them in the cycle like this

        For i = 1 To numberOfPictures
            Dim tmpPicture As New PictureBox

            tmpPicture.Image = cstr(My.Resources.c) & cstr(i) & ".png"
        next

Now this of course doesn't work, because string cannot be converted to System.Drawing.Image. Any ideas how to solve this? I know it's really easy in VB where I did it like this:

        For i = 1 To numberOfPictures
            imgName.Picture = loadPicture(ThisWorkbook.Path & "\picturesfolder\" & CStr(i) & ".png")
        next i

Solution

  • Yes, you can do that like this:

    tmpPicture.Image = DirectCast(My.Resources.ResourceManager.GetObject("c" & CStr(i) & ".png"), Bitmap)
    

    Here's a hint. Sometimes it's very useful to look at the designer code. If you right-click on My.Resources.c1 and choose the Go to Definition option, you'll see the code that is actually executed when you access that property. The c1 property is, obviously, not built in as part of the .NET framework. It's an auto-generated property in a Designer file. The Resources designer screen automatically generates that code for you.