Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to clear a pictureBox?

I tried to set the pictureBox1 Image to null but it didn’t clear it before adding the next image. so each time it’s adding another image it’s adding it on the one before.

then I tried to add a Dispose for the pictureBox1 Image but then it throw exception on the line:

pictureBox1.Image = milimeters[macTrackBar4.Value - 1];

without the Disposing line it’s not throwing the exception but also not clearing the pictureBox1 before adding the next image.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

private void macTrackBar4_ValueChanged(object sender, decimal value)
{
    if (milimeters != null && macTrackBar4.Value > 0 && macTrackBar4.Value <= milimeters.Length)
    {
        // Dispose of the current image if it exists
        if (pictureBox1.Image != null)
        {
            pictureBox1.Image.Dispose();
        }

        // Clear the PictureBox
        pictureBox1.Image = null;
        pictureBox1.Invalidate(); // Invalidate to clear the PictureBox

        // Assign the new image
        pictureBox1.Image = milimeters[macTrackBar4.Value - 1];
    }
}

>Solution :

When assigning a new image to a pictureBox it automatically removes the previous image and replaces it with the new image. There is no need to dispose of the old image unless you want the pictureBox to be blank for an amount of time before switching to the new one. The code below will replace the image of a pictureBox with a new one.

pictureBox1.Image = Resources.MyPicture;

Replace MyPicture with your imported image or resource.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading