Click here to Skip to main content
15,892,537 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In this richtextbox I want to know how many time using "Backspace" on keyboard. So far I already using this code, but something wrong. this is the scenario, When pressing Enter, message box will show how many time using Backspace. Please help me..

What I have tried:

Public Class Form1
    Private Sub RichTextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles RichTextBox1.KeyDown
        Dim count As Integer

        If (e.KeyCode = Keys.Back) Then
            count = count + 1
        ElseIf (e.KeyCode = Keys.Enter) Then
            MessageBox.Show(count)
        End If

    End Sub
End Class
Posted
Updated 16-Sep-18 8:34am

1 solution

count is a local variable, it exists only until the method exits and is recreated and reinitialised each time the method is called by a new event.

You need to make it art of your class declaration by moving it outside the method:
VB
Public Class Form1
    Private count As Integer = 0

    Private Sub RichTextBox1_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
        If (e.KeyCode = Keys.Back) Then
            count = count + 1
        ElseIf (e.KeyCode = Keys.Enter) Then
            MessageBox.Show(count)
        End If
    End Sub
End Class
 
Share this answer
 
Comments
Richard Deeming 18-Sep-18 15:55pm    
Alternatively, you could use a really nasty VB construct:
Static (Visual Basic) | Microsoft Docs[^]
Private Sub RichTextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles RichTextBox1.KeyDown
    Static count As Integer = 0
    
    If (e.KeyCode = Keys.Back) Then
        count = count + 1
    ElseIf (e.KeyCode = Keys.Enter) Then
        MessageBox.Show(count)
    End If
End Sub

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900