简体   繁体   中英

Error in ListView: InvalidArgument = Value of '0' is not valid for 'index'

This error appears when I select some item in ListView for the second time. I tried to debug it, and when I select some item for the second time, the list_answers.SelectedItems.Count is 0. Why? Here is my code:

private void list_answers_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListViewItem t = list_answers.SelectedItems[0];
            for (int i = 0; i < tasks.Count; i++)
            {
                if (t.Text == "Question №" + (i + 1))
                {
                    this.ShowOnePanel(i);
                    iter = i;
                    break;
                }
            }
        }

When changing selection, the ListView will first deselect current row and then select new one, so you will have a call where SelectedItems will be empty.

You can solve it by Adding

if(list_answers.SelectedIndex == -1)
    return;

or

if(list_answers.SelectedItems.Count == 0)
    return;

If you just add this code in the listview_SelectedChangeIndex event, it will solve the problem.

 if (finishListView.SelectedItems.Count > 0)
    {
// here your code goes
    }
    else
    {
    return;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM