I'm trying to use an icon that I've added as a resource as the image on a button. I know it's possible because I can do it in other projects through the designer. However, I'm trying to do this with code. I added the icon as a resource to my project by following the steps in the accepted answer to this question. The resource is named CancelButtonIcon
.
Now, I'm trying to add that icon as the image on a standard button with this code:
this.CancelButton.Image = (System.Drawing.Image)Properties.Resources.CancelButtonIcon;
However, I get an error message:
Cannot convert type 'System.Drawing.Icon' to 'System.Drawing.Image'
In the code that Visual Studio automatically generates when I use the designer, it looks like this:
((System.Drawing.Image)(resources.GetObject("SaveButton.Image")));
which results from manually adding a resource through the Properties window. How can I convert this icon resource to an image so it can be used on the button? Adding it through the designer is not an option (this button is created programmatically and thus isn't present in the designer).
Open the Visual Designer of the form containing the control to change. Select the control. In the Properties pane, select the Image or BackgroundImage property of the control. Select the ellipsis ( ) to display the Select Resource dialog box and then select the image you want to display.
You can use the Icon.ToBitmap
method for this purpose. Note that a Bitmap
is an Image
.
CancelButton.Image = Properties.Resources.CancelButtonIcon.ToBitmap();
Not sure why, but any time I tried using the accepted answer's approach, the .ToBitmap()
call was giving me array index out of bounds exceptions. I solved this by doing it this way instead:
System.Drawing.Icon.FromHandle(Properties.Resources.CancelButtonIcon.Handle).ToBitmap();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With