Access Resource by Name
Using the name of the resource is an effective way of getting to your resources, but the procedure to use is not obvious. This example shows how it’s done.
The My.Resources namespace gives you quick and easy access to your resources. Each resource is a property of the namespace My.Resources. So a resource can be accessed using code such as :
Me.BackgroundImage = My.Resources.Album_3
But what if you don’t know the name of the resource until runtime? An example of this requirement would be that you want to choose the image using a random number. How can you get the ‘n’th image in the resource images?
A simple way to do this is to arrange the resource names so that the name indicates the number. For instance, image resources named as
could be retrieved using this code, where the value passed to the function is a number from 1 to 4.
Me.BackGroundImage = GetAlbumByIndex(I) Function GetAlbumByIndex(ByVal Index As Integer) As Image Dim ImageName As String = "Album_" & Index.ToString Return CType(My.Resources.ResourceManager.GetObject(ImageName), _ System.Drawing.Image) End Function
The resource manager object provides the GetObject method, which takes a resource name. The method returns an object, so the resource must be cast to the correct type before being returned from the function. This form of code can be used to get any resource provided that the resource name can be set into a string variable and the resource type is known.