ArgumentOutOfRangeException for ListViewItem when clicking 2nd time

假装没事ソ 提交于 2019-12-20 07:20:53

问题


The method below when I click second time gives the ArgumentOutOfRangeException error, and says index 0 is not a valid index.

In first click it works!?

ListView FullRowSelect set true.

I see this happens while pressing ALT and CONTROL keys. If I click without pressing those keys it gives no error or If click an empty row before clicking 2nd time it does not give the error.

Is there a way to use those keys combination and clicking more then once ?

    private void MultipleToText(object sender, MouseEventArgs e)
    {
        if (li.SelectedItems.Count <0)
            return;
        int SetIndex = li.FocusedItem.Index;
        if (Control.ModifierKeys == (Keys.Alt|Keys.Control))
        {
            ListViewItem lvi = li.SelectedItems[0];   // Error happens there 
            DialogResult res = MessageBox.Show( lvi.SubItems[0].Text + " will be deleted. Continue ?", "", MessageBoxButtons.YesNo);
            if (res == DialogResult.No)
                return;
            li.Items.Remove(li.SelectedItems[0]);
            RemoveThisItem(SetIndex);
        }
        else if (Control.ModifierKeys == Keys.None)
        {
            ListViewItem lvi = li.SelectedItems[0];
            DialogResult res = MessageBox.Show("Change the entry " +  lvi.SubItems[0].Text + " ?", "", MessageBoxButtons.YesNo);
            if (res == DialogResult.No)
                return;
            li.Items.Remove(li.SelectedItems[0]);
            for (int i = 0; i < 17; ++i)
                _textBox[i].Text = lvi.SubItems[i].Text;
            RemoveThisItem(SetIndex);
        }
    }

回答1:


You are getting an error because your first if statement will never evalute to true (and return) since count will never go below 0. Due to this, even if your list is empty it still tries to delete the first element, throwing an ArgumentOutOfRangeException.

Your if statement should instead check if it is equal to 0, as such:

 if (li.SelectedItems.Count == 0)

Nothing happens when you press anything except Alt/Control because you are not handling the event for any key press other than those,

 Control.ModifierKeys == Keys.None

Means that no keys are pressed as opposed to anything except Alt/Control being pressed.



来源:https://stackoverflow.com/questions/29441223/argumentoutofrangeexception-for-listviewitem-when-clicking-2nd-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!