InvalidArgument=Value of '1' is not valid for 'index'

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Using ListView to achieve ListView click on the item to delete this item effect, call the ItemSelectionChanged event.

The following code:

 private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            listView1.Items.Remove(e.Item);
        }

Abnormal:

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)

 Will be compiled into the EXE runtime will appear this kind of error:

This is because, when you click on the first item, enter the event, first delete later re entered the event, the E is the first value, so the error. Index overflow. The solution is for this operation in the Click event.

 private void listView1_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                listView1.Items.Remove(listView1.SelectedItems[0]);
            }
        }


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Morgan at November 18, 2013 - 12:41 AM