Monday, February 18, 2008

Accessing resources in a non-typed way in VB.NET

OK so the my namespace is really cool, but sometimes we just want more!! to get at a string in the resources of an app is easy. Go to the project tab, add astring resource with the name CompanyName and then type the value in the field nextdoor. Access the value in code like this

label1.text = My.resources.CompanyName

Now intellisense haspicked up the strongly type property and helps you. The same works for images, add an image to the resource file, browse for it and name it Image1. The following code also works:

Picturebox1.Image = My.resources.Image1

Note no need for the extension and also the intellisense pops up again. You just have to love this!!

So now you want to load a random file from the resources, like a random picture..... hmm this strong typing is getting in the way now grrrr.

Do not fret use the resourcemanager, this lets you get to any resource in the current assembly using a string paramater with its name. YES

So imgine you have 10 pics, called 0.jpg, 1.jpg, 2.jpg etc and you want to load them randomly

so the code now looks like this

Dim intNumber as integer = System.Convert.ToInteger(Math.rnd() * 9 )
Picturebox.Image = CType(My.resources.ResourceManager.GetObject(intNumber), Image)


You can also call the GetString method to pull strnig resources in an untyped fashion!!

No comments: