SelectedIndexChanged gives exeption?

I am trying to use the SelectedIndexChanged event in the simplest way possible... the first time the event fires, everything is ok, but the next time I get an Argument Out of Range exeption.

What am I doing wrong here

Any help appreciated

This is the code:-

Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.SelectedIndexChanged

MsgBox(Me.ListView1.SelectedIndices(0))

End Sub



Answer this question

SelectedIndexChanged gives exeption?

  • vanWeyden

    Yep. it wil do it every time. Did it as far back as the first version of this product. Why Because setting the index to zero causes an exception but is not raised until you fire the event the second time.

    Comes back with:

    Value of '0' is not a valid for 'index'.
    Parameter name: index

    Try one of these.

    Dim this As Integer = DirectCast(ListView1.SelectedItems(0), ListViewItem).Index

    Dim this As Integer = CType(ListView1.SelectedItems(0), ListViewItem).Index


  • ssbeginner

    Sorry redwar but that's not going to work. If there are no SelectedIndices then there are no SelectedItems either. The problem is that the first time you select an item you are going from no selected items to one selected item, which is no problem. The next time you select a different item the first thing that happens is the first item is unselected then the new item is selected. This means that the SelectedIndexChanged event is raised twice, once as it the number of selected items changes from 1 to 0 and then again when it changes from 0 to 1. Try this code to see what I mean:

    Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.SelectedIndexChanged

    MessageBox.Show(Me.ListView1.SelectedIndices.Count.ToString())

    End Sub

    This means that you need to test that there are selected items before you try to access them.


  • Naldo Alcalde Huamán

    Thanks, I get it... the event fires twice, when the "old" selected item is deselected, and then again when the "new" item is selected.

    checking for a SelectedIndices.count larger than 0 before using SelectedIndices(0) did the job.

    Thanks again


  • SelectedIndexChanged gives exeption?