user3528837
user3528837

Reputation: 75

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;
                }
            }
        }

Upvotes: 6

Views: 25928

Answers (3)

Darshan Jain
Darshan Jain

Reputation: 838

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;
    }

Upvotes: 3

ceyun
ceyun

Reputation: 381

There is a good description about this problem in the link below:

http://www.vbforums.com/showthread.php?753867-RESOLVED-InvalidArgument-Value-of-0-is-not-valid-for-index-Parameter-name-index

Upvotes: 0

Gusman
Gusman

Reputation: 15151

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;

Upvotes: 10

Related Questions