Label Adding Image Programatically -vs- Adding Image Using The VS2008 Designer

5.8k views Asked by At

I have a C# form that I am creating completely manually (i.e. without using the Visual Studio Design View). In this form I have a Label created (simply) as follows:

private Label myLabel = new Label();

Later on in the code, during a callback, I want to set an image for this label. I have found one way to do it and here is the code:

myLabel.Image = Image.FromFile("Images\\mark.png");

This works but the problem is, when I distribute my application I am going to always have to provide a folder (Images) containing mark.png.

This is acceptable I guess but it's really not what I want...

The interesting thing is, I looked at some other code I created where I used the Visual Studio Design View to add an image to a label and the Designer does it totally different. It somehow parses the image, figures out the binary, and saves the base64 representation of this binary as a string in the .resx file:

<data name="fileDisconnect.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
    <value>
        iVBORw0KGgoAAAANSUhEUgAAABkAAAAXCAYAAAD+4+QTAAAABGdBTUEAAK/INwWK6QAAAAlwSFlzAAAO
        vAAADrwBlbxySQAAAA10RVh0U291cmNlAE51dm9sYaxPNfEAAAAadEVYdFNvZnR3YXJlAFBhaW50Lk5F
        ...
        ...
        ns2di2Jn545YY+PJHw3ZbmREJBgZLDwzgehomExoMpmUG1spVLuhAG/80RSKwyEGo7ZBJNKcsrf/Pd7Q
        MOijAUML48mPeAPCJ5FKhMcSBOt9Ach5ThKVujqeQvEa8v8FrglBl5d/7zYAAAAASUVORK5CYII=
</value>

Looking at the Designer file source code you can see it sets the image lable as follows:

this.fileConnect.Image = ((System.Drawing.Image)(resources.GetObject("fileConnect.Image")));

So, as you can see, doing it this way is much more elegant. There is no need to actually save the image to your hard disk and provide the image when delivering your application. The image information is stored in the .resx file and images are set getting the binary content programatically from the .resx.

My question is.... If I am creating my control manually how can I get the same kind of behavior? Can I create a .resx file, open the image with a HEX editor and copy the binary string into the .resx file? Then, when adding the image to the label I could just just do it like above.

1

There are 1 answers

0
Eric Dahlvang On BEST ANSWER

If you save the image in Resources, you can just do this:

        Label myLabel = new Label();
        myLabel.Text = "whatever";
        myLabel.Image = Properties.Resources.MyLabelImage;
        this.Controls.Add(myLabel);