Jonhston Hirsh
Jonhston Hirsh

Reputation:

C#: Problem with selecting different items after using ListView.SelectedItems[0]

I have a problem, I am using the method in listview ListView.SelectedItems[0] to return the currently selected ListViewItem into an argument in a function that displays the text of the item into a textbox when selected. This method is set to the Listview_SelectedIndexChanged event. The problem is that when I selected a different item now after already previously selecting one, an error comes up that reads,

ArgumentOutOfRangeException was unhandled InvalidArgument=Value of '0' is not valid for 'index' Paramater name: index

Why is it causing that error when I want to return the next currently selected item from my listview? It only occurs after selecting another item after having previously selecting one.

Here is the event:

    private void lvMyItems_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Return currently selected item.
        ShowItem(lvMyItems.SelectedItems[0]); // The error occurs here.
    }

And here is the method that it is calling:

    private void ShowItem(ListViewItem MyItem)
    {
        // This method inputs the text and subitem text of my listview item into two textboxes.
        txtItemName.Text = MyItem.Text;
        txtItemNickName.Text = MyItem.SubItems[1].Text;
    }

Upvotes: 1

Views: 2427

Answers (2)

user1141955
user1141955

Reputation:

I see this problem occur when I click on an item for the second time.

The first click works fine, but the second click results in an exception. I think it's because when we click another item, the program clears the "selection status" for the first item, and marks the second item as "selected". Before marking the second item as "selected", the program will be on the condition where there's no selection item in ListView, which is (most likely) why the program then generates an exception.

So we need to check that the SelectedItems.Count >= 1

Upvotes: 1

Lucero
Lucero

Reputation: 60276

"No selection" is also a possible state. Make sure that SelectedItems.Count >= 1 before accessing the item at index 0.

Upvotes: 4

Related Questions