tags:

views:

482

answers:

1

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;
    }
+4  A: 

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

Lucero
You sir are a genius. Thank you for the solution you provided.