InvalidArgument=Value of '1' is not valid for 'index'
用ListView实现点击ListView的项删除该项的效果,调用ItemSelectionChanged事件。
代码如下:
private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) { listView1.Items.Remove(e.Item); }
发生异常:
System.ArgumentOutOfRangeException: InvalidArgument=Value of '1' is not valid for 'index'. Parameter name: index at System.Windows.Forms.ListView.ListViewItemCollection.get_Item(Int32 index) at System.Windows.Forms.ListView.WmReflectNotify(Message& m) at System.Windows.Forms.ListView.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
编译成EXE运行时则会会出现这种错误提示:
这是因为,当你点击第一项的时候,进入了该事件,第一项删除以后再次进入该事件,此时 e仍为第一项的值,故报错。索引溢出。解决方法是在Click事件中进行此操作。
private void listView1_Click(object sender, EventArgs e) { if (listView1.SelectedItems.Count > 0) { listView1.Items.Remove(listView1.SelectedItems[0]); } }