h3half
h3half

Reputation: 321

button.BackgroundImage = <pngfile> does nothing

I want to change the BackgroundImage of a button when you click once, and then change it back to the original when clicked again (and it will work over and over). My code snippet is this:

private void handButton_Click(object sender, EventArgs e)
    {
        if (handButton.BackgroundImage == WindowsFormsApplication1.Properties.Resources.Hands_Right)
        {
            handButton.BackgroundImage = WindowsFormsApplication1.Properties.Resources.Hands_Left;
        }
        else if (handButton.BackgroundImage == WindowsFormsApplication1.Properties.Resources.Hands_Left)
        {
            handButton.BackgroundImage = WindowsFormsApplication1.Properties.Resources.Hands_Right;
        }
    }

But when I run the program and click the button; nothing happens. The images are 32x32, and I can see the original image clearly. When clicked, the original image stays there. There are no other variables affecting this snippet (at least, a search for "handButton" only gets results from this snippet).

Any suggestions? I have no errors, so I suspect that I'm going about this wrong. Is there a better way to change images back and forth?

Upvotes: 0

Views: 199

Answers (1)

Hans Passant
Hans Passant

Reputation: 942237

The Properties.Resources class doesn't work the way you think. A property like Hands_Right actually returns a new bitmap, not whatever object was returned previously. That wouldn't work very well since modifying the bitmap would also modify the property from its design.

So your if() statement expressions never evaluate to true. Keep track of the button state separately.

Upvotes: 3

Related Questions