这可以检查吗?我无法在MSDN或其他任何地方找到太多帮助。我没有多少if / elses来检查数字是否输入到我的文本框中,我想把它全部放在一个数组或列表中,并根据输入的内容进行简单的包含(不存在)。如果在文本框内输入任何数字,我想要它只是删除文本框中突出显示的空文本。
Private Sub txt_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles fptSSN.KeyPress
Dim i As Integer
Dim keysList As List(Of Keys)
Dim keys() As Keys = {Windows.Forms.Keys.D0, Windows.Forms.Keys.D1, Windows.Forms.Keys.D2, Windows.Forms.Keys.D3, Windows.Forms.Keys.D4, Windows.Forms.Keys.D5, Windows.Forms.Keys.D6, Windows.Forms.Keys.D7, Windows.Forms.Keys.D8, Windows.Forms.Keys.D9, Windows.Forms.Keys.NumPad0, Windows.Forms.Keys.NumPad1, Windows.Forms.Keys.NumPad2, Windows.Forms.Keys.NumPad3, Windows.Forms.Keys.NumPad4, Windows.Forms.Keys.NumPad5, Windows.Forms.Keys.NumPad6, Windows.Forms.Keys.NumPad7, Windows.Forms.Keys.NumPad8, Windows.Forms.Keys.NumPad9}
keysList.AddRange(keys)
If txt.Text = " " And e.KeyChar = ?????????????? Then
txt.Text = ""
End If
Next
End Sub
答案 0 :(得分:3)
由于您正在寻找数字,您可以利用IsNumeric()函数:
If IsNumeric(e.KeyChar) Then
txt.Text = String.Empty
e.Handled = True
End If
如果您不想在清除它时将数字放在文本框中,请设置e.Handled = True。
答案 1 :(得分:2)
您可以使用Any
:
Private Sub txt_KeyPress(ByVal sender As System.Object,
ByVal e As System.Windows.Forms.KeyPressEventArgs) _
Handles fptSSN.KeyPress
Dim keysList As New List(Of Keys)(New Keys() _
{
Windows.Forms.Keys.D0, Windows.Forms.Keys.D1, Windows.Forms.Keys.D2,
Windows.Forms.Keys.D3, Windows.Forms.Keys.D4, Windows.Forms.Keys.D5,
Windows.Forms.Keys.D6, Windows.Forms.Keys.D7, Windows.Forms.Keys.D8,
Windows.Forms.Keys.D9, Windows.Forms.Keys.NumPad0,
Windows.Forms.Keys.NumPad1, Windows.Forms.Keys.NumPad2,
Windows.Forms.Keys.NumPad3, Windows.Forms.Keys.NumPad4,
Windows.Forms.Keys.NumPad5, Windows.Forms.Keys.NumPad6,
Windows.Forms.Keys.NumPad7, Windows.Forms.Keys.NumPad8,
Windows.Forms.Keys.NumPad9
})
If keysList.Any(Function(key) key.Equals(e.KeyChar)) AndAlso txt.Text = " " Then
txt.Text = ""
End If
End Sub