views:

225

answers:

1

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);
        }
    }
+3  A: 

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;
}
Darin Dimitrov