Hello World!
I have a sample code here written in vb .net that restricts the textbox to accept only alpha, alphanumeric or numeric characters.
-
-
Public Enum MyOption
-
Alpha = 1
-
AlphaNumeric = 2
-
Numeric = 3
-
End Enum
-
-
Public Sub SetCharacter(ByVal CharacterOption As MyOption, _
-
ByVal kp As KeyPressEventArgs)
-
Select Case CharacterOption
-
Case MyOptions.Alpha
-
If Not ( _
-
kp.KeyChar Like "[A-Z]" Or _
-
kp.KeyChar Like "[a-z]" Or _
-
kp.KeyChar = vbBack Or _
-
Asc(kp.KeyChar) = 32) Then
-
kp.KeyChar = vbNullChar
-
End If
-
Case MyOptions.AlphaNumeric
-
If Not ( _
-
kp.KeyChar Like "[A-Z]" Or _
-
kp.KeyChar Like "[a-z]" Or _
-
kp.KeyChar Like "[ρΡ]" Or _
-
kp.KeyChar Like "[0-9]" Or _
-
kp.KeyChar = vbBack Or _
-
Asc(kp.KeyChar) = 32) Then
-
kp.KeyChar = vbNullChar
-
End If
-
Case MyOptions.Numeric
-
If Not ( _
-
kp.KeyChar Like "[0-9]" Or _
-
kp.KeyChar = vbBack Or _
-
Asc(kp.KeyChar) = 32) Then
-
kp.KeyChar = vbNullChar
-
End If
-
End Select
-
-
End Sub
Just place the
SetCharacter method to the
KeyPress event of a textbox, combobox, etc.
Sample 1. A textbox that accepts only numeric characters
- Private Sub Text1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Text1.KeyPress
-
SetCharacter(MyOption.Numeric, e)
-
End Sub
As you noticed, the
SetCharacter method has 2 parameters-CharacterOption and kp.
CharacterOption - Sets the MyOption value whether you want alpha, alphanumeric, or numeric
kp - Gets the current key that you have pressed.
Rey Sean
Mabuhay ang pinoy : )