Capturing delete keystroke in ListView control

Hi everyone,

Can someone tell me how I can capture the delete keystroke in a ListView control. Basically, I want to delete the selected row when delete is pressed by the user.

Thanks and cheers!

xargon
xargon_123Asked:
Who is Participating?
 
ShauliConnect With a Mentor Commented:
Private Sub ListView1_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyDelete Then
    ListView1.ListItems.Remove ListView1.SelectedItem.Index
End If
End Sub

S
0
 
fds_fatboyConnect With a Mentor Commented:
Private Sub ListView1_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = vbKeyDelete Then
        MsgBox "Del key pressed"
    End If

End Sub
0
 
fds_fatboyCommented:
Or to do the delete as well...

Private Sub ListView1_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = vbKeyDelete Then
        If Not ListView1.SelectedItem Is Nothing Then
            ListView1.ListItems.Remove ListView1.SelectedItem.Key
        End If
    End If
End Sub
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
fds_fatboyCommented:
Be careful, the answer you accepted, will cause error 91 to occur if you press delete key on an empty listview.
0
 
xargon_123Author Commented:
Well, I have another problem.- The VBA environment does not seem to accept the keydown event for the ListView. Says "The procedure declaration does not match description of event or procedure having the same name"
0
 
fds_fatboyCommented:
Sorry - I didn't realise you were using VBA.

Try this:

Private Sub ListView1_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = vbKeyDelete Then
        If Not ListView1.SelectedItem Is Nothing Then
            ListView1.ListItems.Remove ListView1.SelectedItem.Key
        End If
    End If
End Sub
0
 
fds_fatboyCommented:
Bugger - I copied the wrong thing in..

I meant

Private Sub ListView1_KeyDown(KeyCode As Integer, ByVal Shift As Integer)
...

But I've just tried it (VBA is not my forte) and it doesn't detect Del key.
0
 
fds_fatboyCommented:
You could set the KeyPreview asnd capture the keystroke in the form - this appears to work in Access VBA:

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = vbKeyDelete And Me.ActiveControl Is ListView1 Then
        If Not ListView1.SelectedItem Is Nothing Then
            ListView1.ListItems.Remove ListView1.SelectedItem.Index
        End If
    End If
End Sub

Private Sub Form_Load()
    Me.KeyPreview = True
End Sub

0
All Courses

From novice to tech pro — start learning today.