4
Answers

PictureBox memory leak

wouterk

wouterk

14y
14.2k
1
Hello,

I'm trying to show a selected image from a ListView in a PictureBox.

When I select an Image from the ListView it does show up. but each time I do this the memory usage of my app shoots up and doesn't go down (I'm using rather big images)

Working code with memory issue:
        Bitmap originalImg;

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Selected == true)
{
originalImg = new Bitmap(folderPath + "/" + listView1.Items[i].SubItems[0].Text);
}
}

pictureBox1.Image = tempImg;
}


I tried disposing the image before another one is loaded but I get a null pointer exception the second time an image is selected in the ListView.

        Bitmap originalImg, tempImg;

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Selected == true)
{
tempImg = new Bitmap(folderPath + "/" + listView1.Items[i].SubItems[0].Text);
}
}

originalImg = (Bitmap)tempImg.Clone();
tempImg.Dispose();
OriginalPictureBox.Image = originalImg;
}
}

What am I overlooking?

Thanks in advance :)
Answers (4)