I have a ListView which I populate with the contents of an ImageList. When an Item is selected from the list, I check if the file still exists. If it doesn't, I want to remove it both from the Image List (which is private static) and from the ListView. For some strange reason, which I can't figure out, after removing the selected image from the list, the image right after it disappears and the last image in the list appears twice. For example, if the list held the following images: IMG1, IMG2, IMG3, IMG4, IMG5 and I remove IMG2 the new list will look like this: IMG1, IMG4, IMG5, IMG5.
Furthermore, if I select the second image from the list (which is now IMG4) and display it in some picture control, IMG3, which was supposed to be in that place will be displayed in the control.
Any ideas what's going on here?
EDIT: Populating the List view:
private static ImageList stampsImages
if (stampsImages == null)
{
stampsImages = new ImageList();
stampsImages.ImageSize = new Size(125, 75);
}
DirectoryInfo di = new DirectoryInfo(Globals.Directory);
if (di.Exists)
{
FileInfo[] dFiles = di.GetFiles("*.png");
int stampListSize = stampsImages.Images.Count;
for (int i = 0; i < dFiles.Length; i++)
{
int idx = stampsImages.Images.IndexOfKey(dFiles[i].FullName);
if (idx < 0)
{
stampsImages.Images.Add(Bitmap.FromFile(dFiles[i].FullName));
stampsImages.Images[stampListSize].Tag = dFiles[i].FullName;
stampsImages.Images.SetKeyName(stampListSize, dFiles[i].FullName);
stampListSize++;
}
}
}
else di.Create();
for (int i = 0; i < stampsImages.Images.Count; i++)
{
ListViewItem stmp = new ListViewItem("", i);
lvwStamps.Items.Add(stmp);
}
lvwStamps.LargeImageList = stampsImages;
Checking if the file still exists:
private bool IsStampAvailable(int listIdx)
{
bool stampExists = true;
string stampFile = stampsImages.Images.Keys[listIdx];
if (!File.Exists(stampFile))
{
lvwStamps.Items.RemoveAt(listIdx);
stampsImages.Images.RemoveAt(listIdx);
stampExists = false;
}
return stampExists;
}