Wierd windows forms ListView Issue, bug in .NET?

While working on a decent sized Windows Forms app in c#, I've seen a sporadic issue crop up that is incredibly difficult to debug.   The form simply has a listview on it that is populated from a worker thread.   The calls are all done with Invoke, on the UI thread.   But, every once and awhile (it's sporadic). .NET throws this:

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Windows.Forms.ListViewItemCollection.get_Item(Int32 displayIndex)
  at System.Windows.Forms.ListView.OnHandleDestroyed(EventArgs e)
   at System.Windows.Forms.Control.WmDestroy(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ListView.WndProc(Message& m)
   at System.Windows.Forms.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.ComponentManager.System.Windows.Forms.UnsafeNativeMethods+IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.RunDialog(Form form)
   at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
   at System.Windows.Forms.Form.ShowDialog()

I can't find out where this is coming from, it has no reference to anything in the app, it's all in the framework. 

Anyone seen this?

4 Comments

  • VS 2005 lets you see the .NET Framework source code.

  • I came across with the same problem. In my specific case was that I drew a ListView Control onto a TabControl, causing me this same Exception.

    I just deleted the TabControl, place the ListView onto the form and voila! It worked!

  • I have this same problem with my application which has a listview on a winform. This form is refreshed by a timer of one second. Sometimes it throw the exception above. Do somebody know the solution for this?

  • This may occur if the form is closed and then the background thread starts an update.

    You may get a related error if the background thread starts to update the listview before the handle for the form has been created (i.e. a very short time after the form's constructor runs). To prevent this, ensure the handle is created in the form's constructor by referencing it:
    IntPtr x = this.Handle; // this is sufficient.

Comments have been disabled for this content.