I am making an album application with windows forms and I have a problem that I can't solve. First of all I have a form where I create a TableLayoutPanel. After that I create a method where I generate the same amount of picture boxes as the amount of the images in the directory which I have opened. The problem occurs when I am trying to dispose the image which I load in the picturebox because I need to free its memory. Here is the code of the method:
public void createPictureBoxes()
{
Image loadedImage;
int imageCounter = 0;
for (int i = 0; i < rowCounter; i++)
for(int p = 0; p < imagesTable.ColumnCount; p++)
{
PictureBox pb = new PictureBox();
pb.SizeMode = PictureBoxSizeMode.Zoom;
pb.Width = imagesTable.GetColumnWidths()[p];
pb.Height = imagesTable.GetRowHeights()[i];
pb.Click += new EventHandler(enlargeThumbnail);
try
{
loadedImage = Image.FromFile(images[imageCounter++]);
pb.Image = loadedImage;
loadedImage.Dispose();
imagesTable.Controls.Add(pb);
loadedImage.Dispose();
}
catch (IndexOutOfRangeException)
{
break;
}
}
}
The program throws an ArgumentException on method Show() of the form telling me that the argument is not valid. Without the dispose method all works fine but if i try to load a large amount of images the program uses gigabytes of memory. I suppose that it is not right to dispose the image memory that way, but I can't come out with another idea. If someone could help I would be very grateful