[Solved] To clear loaded images in a picturebox-c#


Your code has many issues.

The one you are looking for is that you don’t clear the alist before loading new file names.

So insert:

    alist.Clear();

before

    //Get Each files 

And also

   filelength = alist.Count;

after the loop. No need to count while adding!

Also note that ArrayList is pretty much depracated and you should use the type-safe and powerful List<T> instead:

List<string> alist = new List<string>();

Of course a class variable named i is silly and you are also relying on always having a SelectedItem in the comboBox2.

And since you are not properly Disposing of the Image you are leaking GDI resources.

You can use this function for properly loading images:

void loadImage(PictureBox pbox, string file)
{
    if (pbox.Image != null)
    {
        var dummy = pbox.Image;
        pbox.Image = null;
        dummy.Dispose();
    }
    if (File.Exists(file)) pbox.Image = Image.FromFile(file);
}

It first creates a reference to the Image, then clears the PictureBox‘s reference, then uses the reference to Dispose of the Image and finally tries to load the new one.

solved To clear loaded images in a picturebox-c#