你好,世界!
我这里有一个用vb .net编写的示例代码,该代码将文本框限制为仅接受字母,字母数字或数字字符。
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
只需将SetCharacter方法放置到文本框,组合框等的KeyPress事件中即可。
示例1.一个仅接受数字字符的文本框
Private Sub Text1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Text1.KeyPress
SetCharacter(MyOption.Numeric, e)
End Sub
如您所见, SetCharacter方法具有2个参数-CharacterOption和kp。
CharacterOption-设置MyOption值是需要字母,字母数字还是数字
kp-获取您按下的当前键。
雷伊·肖恩
Mabuhay ang pinoy:)