ListView.Items.RemoveAt causes NullReferenceException
See original GitHub issue-
.NET Core Version: 6.0.0
-
Have you experienced this same bug with .NET Framework?: Classic .NET - No .NET 5 - No .NET 6 - Yes
Problem description: Deleting a selected item from ListView causes NullReferenceException on calling ListView.Items.RemoveAt(index). The bug reproduces stable in my app in the following conditions:
- The item being deleted must be selected. If it’s not selected, no error.
- To workaround the error, we can call ListView.Focus() before delete.
- ListView is a Details view.
The code that fails: `
// listView1.Focus(); // helps to avoid error
listView1.Items.RemoveAt(0); // error is here if item 0 is selected
MessageBox.Show("a"); // shows after error
`
Despite the error, the item is deleted.
Error stack: System.NullReferenceException: Object reference not set to an instance of an object. at System.Windows.Forms.ListViewItem.get_AccessibilityObject() at System.Windows.Forms.ListView.ListViewAccessibleObject.GetFocus() at System.Windows.Forms.ListView.OnGotFocus(EventArgs e) at System.Windows.Forms.Control.WmSetFocus(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ListView.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, WM msg, IntPtr wparam, IntPtr lparam)
Expected behavior: No error in the above case. Because it worked well before .NET 6.
Minimal repro: I couldn’t create a small app to reproduce the error, because there is no error in a simple app. However, I hope that a developer who works daily on WinForms, can find the possible mistake in ListViewItem.get_AccessibilityObject() Edit: the test app is attached below.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:8 (4 by maintainers)

Top Related StackOverflow Question
@vladimir-krestov @SergeySmirnov-Akvelon please investigate
Hi @MelonWang1, it looks like you just commented on a closed issue. The team will most probably miss it. If you have a question - consider opening a new discussion thread. Alternatively, you’d like to bring something important up to their attention, consider filing a new issue and add enough details to build context.