• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1214
  • Last Modified:

How to create a backspace button in VB 2008


I have created a simple calculator for class with a few issues yet to be resolved.  I need to implement the following features:  +/- button, a decimal (only once), and a backspace.  I found this resource online that seems to address some of these issues i'm having but do not know how to implement it.  Can someone help me or give me clues as to how or where i should look to try to solve this?


1 Solution
Try thi, from http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress.aspx

Private nonNumberEntered As Boolean = False

    ' Handle the KeyDown event to determine the type of character entered into the control.
    Private Sub textBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) _
         Handles TextBox1.KeyDown
        ' Initialize the flag to false.
        nonNumberEntered = False

        ' Determine whether the keystroke is a number from the top of the keyboard.
        If e.KeyCode < Keys.D0 OrElse e.KeyCode > Keys.D9 Then
            ' Determine whether the keystroke is a number from the keypad.
            If e.KeyCode < Keys.NumPad0 OrElse e.KeyCode > Keys.NumPad9 Then
                ' Determine whether the keystroke is a backspace.
                If e.KeyCode <> Keys.Back Then
                    If (e.KeyCode <> Keys.OemPeriod) Then
                        ' A non-numerical keystroke was pressed.
                        ' Set the flag to true and evaluate in KeyPress event.
                        nonNumberEntered = True
                        If (InStr(TextBox1.Text, ".") > 0) Then
                            nonNumberEntered = True
                            nonNumberEntered = False
                        End If
                    End If
                End If
            End If
        End If
    End Sub 'textBox1_KeyDown

    ' This event occurs after the KeyDown event and can be used
    ' to prevent characters from entering the control.
    Private Sub textBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) _
        Handles TextBox1.KeyPress
        ' Check for the flag being set in the KeyDown event.
        If nonNumberEntered = True Then
            ' Stop the character from being entered into the control since it is non-numerical.
            e.Handled = True
        End If
    End Sub 'textBox1_KeyPress
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Tackle projects and never again get stuck behind a technical roadblock.
Join Now