Click here to Skip to main content
15,920,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Change the image of the button when clicking the button. ex: When I click for the first time, the number 1 image should come and after clicking the second time, the image of number 2 should come and when I click for the third time, the image of number 1 should come.

What I have tried:

private void Connectbtn_Click(object sender, EventArgs e)
           Image bkg = Image.FromFile(@"D:\Documents\New folder\img1.PNG");
           Image bk = Image.FromFile(@"D:\Documents\New folder\img2.PNG");

           if (Connectbtn.Enabled)
               Connectbtn.BackgroundImage = bkg;
               Connectbtn.BackgroundImage = bk;

this is not working 
Updated 21-Apr-23 7:08am

1 solution


this is not working
this is probably the most useless problem report we get - and we get it a lot. It tells us nothing about what is happening, or when it happens.
So tell us what it is doing that you didn't expect, or not doing that you did.
Tell us what you did to get it to happen.
Tell us any error messages.
Use the "Improve question" widget to edit your question and provide better information.

Otherwise, we have to guess what might possibly be going wrong with your app!
In this guess, I see one obvious problem ... which may or may not be the one you have met!

Start with the documentation: Image.FromFile[^]:
Managed GDI+ has built-in encoders and decoders that support the following file types:






The file remains locked until the Image is disposed.

If the file does not have a valid image format or if GDI+ does not support the pixel format of the file, this method throws an OutOfMemoryException exception.
What the bit in bold means is that the first time you click the button it'll load the two images: the second time it won't and your app will throw an exception.

Instead of that, load your two images into static readonly Image variables as part of your static form constructor and use those as your button images.

Or better, add the images as resources to your application and use them directly from there.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900