I am building a ListView
to display images to the user.
In the form constructor, I load all the images then the form is displayed. Then an ArgumentException
is thrown in the ShowDialog()
function:
Message: The parameter is not valid
ParamName: null
InnerException: null
Source: System.Drawing
StackTrace:
System.Drawing.Image.get_Width() System.Drawing.Image.get_Size() System.Windows.Forms.ImageList.CreateBitmap(Original original, Boolean& ownsBitmap) System.Windows.Forms.ImageList.CreateHandle() System.Windows.Forms.ImageList.get_Handle() System.Windows.Forms.ListView.RealizeProperties() System.Windows.Forms.ListView.OnHandleCreated(EventArgs e) System.Windows.Forms.Control.WmCreate(Message& m) System.Windows.Forms.Control.WndProc(Message& m) System.Windows.Forms.ListView.WndProc(Message& m) System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
I am using a solution from here in order to be able to delete images when the user requires so. If I don't use the solution and don't use the using block, it works fine. However I won't be able to delete images anymore.
Here is my code. Note that the method always execute to the end (I checked this using breakpoints). The exception is thrown only when I call ShowDialog()
:
private void LoadImages()
{
lv_Images.LargeImageList = new ImageList();
lv_Images.LargeImageList.ImageSize = new Size(64, 64);
DirectoryInfo di = new DirectoryInfo(initialDirectory);
foreach (FileInfo file in di.EnumerateFiles())
{
if (isImage(file)) //Simply checks the file extension
{
using (Image img = Image.FromFile(file.FullName))
{
lv_Images.LargeImageList.Images.Add(file.Name, img);
}
int index = lv_Images.LargeImageList.Images.IndexOfKey(file.Name);
lv_Images.Items.Add(file.Name, file.Name, index);
}
}
}
What I think is strange though is that it works fine when I call the LoadImages()
method from the Shown
event of the form.
So I'm not really stuck as I have a workaround but I am curious on why this exception is thrown.