ARTICLE

TextBox keypress event in VB.NET

Posted by Rohatash Kumar Articles | Windows Forms VB.NET June 02, 2011
This article defines that user can enter only numbers in the textbox and deny rest.
 
Reader Level:

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.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles 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.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles 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.

keypress2.gif

Figure3

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

keypress3.gif

Figure4

Login to add your contents and source code to this article
share this article :
post comment
 
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Team Foundation Server Hosting
Become a Sponsor