KnowDotNet Visual Organizer

SelectedIndexChange Event Fires Twice in ListView

Protect the SelectedIndexChange Event

by Les Smith
Print this Article Discuss in Forums

Why does the SelectedIndexChange Event fire twice when an item is clicked in the ListView?  Referencing the SelectedItems Collection on the first firing will cause an error, "Specified argument was out of range of valid values."

This is one of those errors that you correct for when it hits you and then, unless your memory is longer than mine, you will get hit by it again.

MSDN states, and I quote, "The SelectedIndexChanged event occurs in single selection controls, whenever there is a change to the index position of the selected item. In a multiple selection control, this event occurs whenever an item is removed or added to the list of selected items."

The documentation is not correct for single selection controls.  Except for the first time you click in the ListView, the SelectedIndexChange event fires twice.  The reason for the two firings is that, even in a single-select control (MultiSelect property is False), it fires when you click on a new item; once to register that an item has been unselected and second to say the new item has been selected.  I said that it does not happen on the first click because there was nothing selected the first time you click, so you only get one firing of the event.

The problem arises when the first firing occurs (after the second or subsequent click), becaues the SelectedItems Collection has a count of zero.  So, if without testing the count, you attempt to reference an item in the SelectedItems Collection, you will get an error, "Specified argument was out of range of valid values."

The following code will protect you from getting the exception.

   Private Sub lvWQ_SelectedIndexChanged( _
      
ByVal sender As Object, _
      
ByVal e As System.EventArgs) _
      
Handles lvWQ.SelectedIndexChanged
    
' Ensure there are items in the collection
      
If lvWQ.SelectedItems.Count > 0 Then
         Dim i As Integer = lvWQ.SelectedItems(0).Index
      
End If
   End Sub

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing