Monday, September 1, 2008

Useful code in VB2005 to lock input key

This code is written in the keypress event handler. It will lock the type of key. So, user won't type the restricted key(s), which is defined by the programmer.
Beside alphabet and digit, this code also available for keys like quotation, which will cause error for input into database by using SQL query.
Example code below means user only can input digit and plus symbol.

----------------------------------------------------------------------------------
Private Sub txtphone_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txttelp.KeyPress
If Not (Char.IsDigit(e.KeyChar) OrElse Char.IsControl(e.KeyChar)) AndAlso Not e.KeyChar = "+"c Then e.Handled = True
End Sub
----------------------------------------------------------------------------------

Try it yourself, it really works!!!

No comments: