TextBox keypress event in VB.NET

This article defines that user can enter only numbers in the textbox and deny rest.
  • 19159

This article defines that user can enter only numbers in the textbox and deny rest.

KeyPress Event

This Occurs when a key is pressed while the control has focus.

example-1

This example define simple effect of the KeyPress Event when we press any key.

VB code

Public Class Form1

    Private Sub TextBox1_KeyPress(ByVal sender As System.ObjectByVal e AsSystem.Windows.Forms.KeyPressEventArgsHandles TextBox1.KeyPress

        MessageBox.Show("KeyPress")

        e.Handled = True

    End Sub

End Class

Now run the application and press any key. This will display a message Box.

keypress4.gif

Image1

Example-2

This example defines that a user can enter only numbers in the textbox and deny rest.

VB Code

Public Class Form1

    Private Sub TextBox1_KeyPress(ByVal sender As System.ObjectByVal e AsSystem.Windows.Forms.KeyPressEventArgsHandles TextBox1.KeyPress

        If (e.KeyChar < Chr(48) Or e.KeyChar > Chr(57)) And e.KeyChar <> Chr(8) Then

            e.Handled = True

  MessageBox.Show("Please enter only number")

        End If

    End Sub

End Class

Now run the application.

 keypress1.gif

Figure2

Now enter number it will work fine.

3.gif

Figure3

Now enter the character in the textbox. This will display an error.

 4.gif

Figure4

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.