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 :)
Felipe RamosPosted Nov 10, 2010, 10:19 AM
wouterkPosted Nov 10, 2010, 4:41 AM
adding the lines:
if (OriginalPictureBox.Image != null)
{
OriginalPictureBox.Image.Dispose();
}
Did the trick.
Full code:
if (OriginalPictureBox.Image != null)
{
OriginalPictureBox.Image.Dispose();
}
wouterkPosted Nov 9, 2010, 5:20 PM
No particular reason for the two global bitmaps, just an attempt to fix the problem.
I tried your solution but the memory usage of my app still goes up (by the amount of the size of the picture) each time a picture from the listView is selected, even if the picture has been selected before, so switching between just 2 images results in increasing memory usage up to the point where an 'Out of memery exception' occurs.
It seems like somewhere a copy of the image is kept in the memory :(
commenting the line: OriginalPictureBox.Image = new Bitmap(folderPath + "/" + listView1.Items[i].SubItems[0].Text);
results in a stable memory usage, but ofcourse the picture is not loaded. (so I think it's safe to assume it has to do something wiith that particular line)
(and indeed that adding that 'break;' was a good idea :D, thanks! )
Felipe RamosPosted Nov 9, 2010, 4:51 PM