ListView cancel SelectedIndexChanged

AndyMC

Member
Joined
Feb 12, 2003
Messages
10
I would like to cancel the SelectedIndexChanged event if a validation fails.

As there is no event that I can cancel I have to write a workaround that sets the selected item back to the (remembered) old selected item if the validation fails (see code below).

It works so far as that I can set back the selection to the old item but in my GUI the new selected item (that I dont want to be selected) is still selected and the old one (that I selected "manually") is not being selected.

Can anyone help?
Thanks in advance
Andy

Code:
Private Sub ctlSortableListView_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.SelectedIndexChanged
        Dim newSelectedIndex As Integer
        Dim cancel As Boolean

        newSelectedIndex = SelectedItemIndex

        RaiseEvent SelectedItemChanged(cancel, mOldSelectedIndex, newSelectedIndex)
        If cancel = True Then
            Me.Items(newSelectedIndex).Selected = False
            Me.Items(mOldSelectedIndex).Selected = True  set back to old value, if canceled outside.
             This doesnt work. The selection is being changed (internally) but still the "newSelectedIndex" row seems to be selected (in the GUI) and not the "oldSelectedIndex" row.
             This seems to be a bug in the listView control!?
        Else
            mOldSelectedIndex = newSelectedIndex
        End If
        Me.Refresh()
    End Sub

    Protected Overrides Sub OnSelectedIndexChanged(ByVal e As System.EventArgs)
        Dim newSelectedIndex As Integer
        newSelectedIndex = SelectedItemIndex
        If newSelectedIndex <> mOldSelectedIndex And newSelectedIndex > -1 Then only raise event, when selection really changed
            ctlSortableListView_SelectedIndexChanged(Me, e)
        End If
    End Sub
 
I dont know if you are still looking for an answer. But if you are, this might help (doesnt work with keyboard navigation).

[VB]
Private Sub ListView1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.Click
If ListView1.SelectedIndices.Count = 0 Then
Exit Sub
End If

Check if its the same item thats clicked again.
If selectedIndex = ListView1.SelectedIndices.Item(0) Then
Exit Sub
End If

Do the validation
If valid() Then
selectedIndex = ListView1.SelectedIndices.Item(0)
Else
ListView1.Items(selectedIndex).Selected = True
ListView1.EnsureVisible(selectedIndex)
End If
End Sub
[/VB]
 
Last edited by a moderator:
Back
Top