简体   繁体   中英

Switching PictureBox Images C#

I'm trying to make a "checkbox" that has a custom check image. I need it to toggle between checked and unchecked when the user clicks the picturebox. I've tried the following code, and the first click shows the checked image fine, however a second click does nothing. Any ideas?

    private void pictureBox7_Click(object sender, EventArgs e)
    {
        if (pictureBox7.Image == Image.FromFile(checkedImg))
        {
            pictureBox7.Image = Image.FromFile(uncheckedImg);
        }
        else
        {
            pictureBox7.Image = Image.FromFile(checkedImg);
        }
    }

Your if statement is wrong as it is unlikely to return true because you are comparing instances of the Image class which you recreate every time. You could modify it like this:

private bool _pbChecked = false;
private void pictureBox7_Click(object sender, EventArgs e)
{
    var pictureBox = (PictureBox)sender;
    string imgPath = _pbChecked ? uncheckedImg : checkedImg;
    pictureBox.Image = Image.FromFile(imgPath);
    _pbChecked = !_pbChecked;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM