Search code examples
c#toolstripbutton

ToolStripButton: what's wrong with assigning an image programmatically


There is a Form with a ToolStrip. This ToolStrip contains a ToolStripButton. I want to assign an image to this button:

this.btnSaveFile.Image = Bitmap.FromFile("C:\\Work\\Icons\\png\\save.png");

It works only if there is save.png on specified path. Otherwise, I get an FileNotFound Exception.

If I created a Form via Form Designer, Visual Studio would create a code like this:

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

toolStripButton9.Image here is not a real name. Visual Studio takse my file save.png and transform it into toolStripButton9.Image.

But I create a form programmatically, without Designer. And my question is how to assign an image to the ToolStripBotton programmatically?

I tried to add the image to the project, but it didn't help much. I have no idea how to make Visual Studio grab it and embed into my executable so that I wouldn't need this file on specified location.

In MSDN, I only see the solution like that:

this.toolStripButton1.Image = Bitmap.FromFile("c:\\NewItem.bmp");

But it doesnt' work as I told above. I understand there is a simple solution but don't see it. Could you please give me a hint?


Solution

  • In Visual Studio, Open your "Properties" folder in the solution explorer, then open the Resources.resx file and add a existing image file as resource. You can then use it programmatically via the Resource static class:

    Image x = Resources.MyResourceImage;
    

    A full example of the code I suggest:

    using System.Windows.Forms;
    using Testapplication.Properties;
    
    namespace Testapplication {
        public class Class1 {
            public Class1() {
                Form MyForm = new Form();
                ToolStrip MyToolStrip = new ToolStrip();
                MyForm.Controls.Add(MyToolStrip);
    
                ToolStripButton MyButton = new ToolStripButton();
                MyToolStrip.Items.Add(MyButton);
    
                MyButton.Image = Resources.MyResourceImage;
    
                MyForm.Show();
            }
        }
    }
    

    Don't forget to add a using to YourApps' Properties namespace. Your Resources.resx (.cs) file resides in that namespace and is used to provide strong-types object references like images. In your case, replace "MyResourceImage" with "save" (omit the quotes).

    ps. A glance at the most important part of my Resources.designer.cs file:

    internal static System.Drawing.Bitmap MyResourceImage {
        get {
            object obj = ResourceManager.GetObject("MyResourceImage", resourceCulture);
            return ((System.Drawing.Bitmap)(obj));
        }
    }