Programmers’ Log

foreach(Snippet aSnippet in ProgrammersLog){ aSnippet.GetSolution(); }

Resource Managers and VS (Visual Studio) — a better understanding

leave a comment »

Have you ever tried to find out what happens if you add a picture box and import an image in to it. Lets peep in to such a senario.

The usual one

Here we add a pictuebox and we use the properties window to assign it some image after importing it to the resource file.

When we run the application, we will be able to see the image in the picturebox.

The hidden one

When you add a picture control and an image to it, a lot of things are done in the background by the VS. It may appear to be easy but its really frustrating as such a process is not transparent. Each and every project will have a resource file by the name Resource.resx. When you double click it, you may get a string table or an image area, but actually its an xml file. Try opening the same file using right click and ViewSource — you will see an xml file. Now when you add any images or strings to such a table you are actually writing xml tags. But VS does it for you. Lets try to do the job of VS now.

  • Put a picture box in to your form
  • Open the resource file (xml form of the file)
  • Open the WindowsExplorer and navigate to the project folder
  • Create a folder called Resources under your project folder (this folder will be automatically created if you try to add some images to the resource file)
  • Put some bitmaps under this folder (say 1.bmp, 2.bmp and so on)
  • Coming back to the xml file, write the following


<data name="image1" type="System.Resources.ResXFileRef">
<value>..\..\Resources\1.bmp;System.Drawing.Bitmap</value>
</data>

Now go to your class and start accessing the image that you have added manually using the following snippet

pictureBox1.Image = global::<your_name_space>.Resource.image1

Now try running the application. You should be seeing the image on the pictureBox.

Whats the meaning ??

In the xml file the data tag’s name attribute will be like a variable name (some kinna id) and the name given for your image in here will be image1 and the type attribute will tell the .NET csc that its a resource that is linked in to the project. The value tag is the one that can be replaced with the path of any images (full file name). So ..\..\ … refers to the path of the image and the statement after ; tells the csc that the referenced resource object is of type Bitmap and to use System.Drawing.Bitmap class to create an object for it (object’s name will be ?? image1). This is what is happenning in VS when you add an image to the resource file.

Written by sudarsanyes

July 15, 2008 at 10:22 pm

Posted in C#, UI

Tagged with , , ,

Leave a Reply