鉴于texbox,我怎样才能完全忽略非数字字符?因此,如果我按“A”或“Z”,这些字符将永远不会出现在文本框中。如果用户试图输入数字并且他也试图输入非数字,我想运行一些代码..
答案 0 :(得分:5)
试试这个
Private Sub textBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles textBox1.KeyPress
If Char.IsDigit(e.KeyChar) Then
e.Handled = False
Else
e.Handled = True
End If
End Sub
如果对于非数字,e.Handled
设置为true,则没有输入将转到文本框;否则事件消息会像往常一样流动。
编辑:
要处理BackSpace和删除是一项更多的工作,但你可以试试这个
Private Sub textBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles textBox1.KeyPress
If Char.IsDigit(e.KeyChar) OrElse e.KeyChar = CChar(Keys.Delete) OrElse e.KeyChar = CChar(Keys.Back) Then
e.Handled = False
Else
e.Handled = True
End If
End Sub
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
If keyData = Keys.Delete OrElse keyData = Keys.Back Then
OnKeyPress(New KeyPressEventArgs(CChar(keyData))
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
对于Delete和Backspace键不会触发KeyPress事件,因此重写ProcessCmdKey以手动调用表单的OnKeyPress()
答案 1 :(得分:0)
您可以在OnKeyPress事件中运行测试(或者winforms中的任何事件名称)
答案 2 :(得分:0)
一种方法是使用“MaskedTextBox”控件并设置其方便的“Mask”属性
答案 3 :(得分:0)
以下代码有效:
Private Sub txtSalary_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSalary.KeyPress
If (e.KeyChar < Chr(48) Or e.KeyChar > Chr(57)) And e.KeyChar <> Chr(8) Then
e.Handled = True
End If
End Sub