[RESOLVED] Gettings values from SelectedItems.Subitems Error
I was testing to get the values from the ListView which works fine when double-clicking a row in the MouseDoubleClick_event, but in the SelectedIndexChange_event it crashes. I get an error that the value of "0" is not valid for the index.
vb.net Code:
Private Sub lstv_gegevens_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstv_gegevens.SelectedIndexChanged
MsgBox(lstv_gegevens.SelectedItems(0).SubItems(2).Text)
End Sub
Re: Gettings values from SelectedItems.Subitems Error
If you read the documentation for ListView class, you'll find that the SelectedIndexChanged event is raised everytime a listview.SelectedIndices collection changed.
Furthermore, MSDN also remarks:
Code:
The SelectedIndices collection changes whenever the Selected property of a
ListViewItem changes. The property change can occur programmatically or
when the user selects an item or clears the selection of an item. When the
user selects an item without pressing CTRL to perform a multiple selection,
the control first clears the previous selection. In this case, this event occurs
one time for each item that was previously selected and one time for the
newly selected item.
Thus, you just have to check the count on SelectedItems before trying to access an item from the collection.
Code:
Private Sub lstv_gegevens_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstv_gegevens.SelectedIndexChanged
If lstv_gegevens.SelectedItems.Count > 0 Then
MsgBox(lstv_gegevens.SelectedItems(0).SubItems(2).Text)
End If
End Sub
Re: [RESOLVED] Gettings values from SelectedItems.Subitems Error
The problem has been solved with you code, but what I don't understand is that it happens when there totally was no intension to select multiple rows. I just clicked a new row.
Thanks anyway ;)
Re: [RESOLVED] Gettings values from SelectedItems.Subitems Error
It happens exactly as the remark mentions. When you select another listviewitem, the control clear out the previous selection and raise the event. And this is when you try to access items(0) where the collection has no items. The control then add the current selected item to the collection and raise the event again. This time is the valid one that you want to catch. By counting the selected items in the collection, you can omit all the "false" events and only act on the valid one.
Re: [RESOLVED] Gettings values from SelectedItems.Subitems Error