Home Ask Login Register

Developers Planet

Your answer is one click away!

Patrick February 2016

Simple ON/OFF toggle button with image

I'm working on a WinForms project where I'm trying to create an ON/OFF toggle button that uses two separate images (both located in project resources) for both the "ON" setting, and the "OFF" setting.

Based on what I've found online, I've used a CheckBox with its appearance set to "Button".

Here is the code I've got so far for my button:

    private void ToggleButton_CheckedChanged(object sender, EventArgs e)
    {
        if (ToggleButton.Checked)
        {
            ToggleButton.BackgroundImage.Equals(Properties.Resources.ToggleButton_ON);
        }
        else
        {
            ToggleButton.BackgroundImage.Equals(Properties.Resources.ToggleButton_OFF);
        }
    }

For some reason nothing happens when I click on the button, and I'm not sure what I've done wrong here.

Basically, I'd like the background image to cycle back and fourth between ToggleButton_ON and ToggleButton_OFF when the user clicks on the button.

Answers


Vahid K. February 2016

Change your code to:

   private void ToggleButton_CheckedChanged(object sender, EventArgs e)
    {
        if (ToggleButton.Checked)
            ToggleButton.BackgroundImage = Properties.Resources.ToggleButton_ON;
        else
            ToggleButton.BackgroundImage = Properties.Resources.ToggleButton_OFF;
    }

The .Equals is for checking equality which you can override in your own classes.

Post Status

Asked in February 2016
Viewed 2,646 times
Voted 4
Answered 1 times

Search




Leave an answer


Quote of the day: live life