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

.netc++winforms

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

Best Solution

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

Related Question