Link to home
Start Free TrialLog in
Avatar of xargon_123
xargon_123

asked on

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
SOLUTION
Avatar of fds_fatboy
fds_fatboy

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of fds_fatboy
fds_fatboy

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
Be careful, the answer you accepted, will cause error 91 to occur if you press delete key on an empty listview.
Avatar of xargon_123

ASKER

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"
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
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.
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