Click here to Skip to main content
13,702,595 members
Rate this:
 
Please Sign up or sign in to vote.
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 3 days ago
Updated 3 days ago

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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:
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
  Permalink  
Comments
Richard Deeming yesterday
   
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web01-2016 | 2.8.180906.1 | Last Updated 16 Sep 2018
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100