传递一个函数来验证数字只有vb.net

时间:2016-08-14 02:02:34

标签: vb.net

所以我有这个文本字段,我只想输入数字值 我能用这段代码做到这一点

   .KeyPress //using a keypress event 

            If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso
                e.KeyChar <> ControlChars.Back Then
                e.Handled = True
            End If

        End Sub

上面的代码工作正常但我想知道我是否可以将它作为一个函数传递并在需要时调用该函数 像这样的事情:

private Function Numbers_Only()

    If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso
                    e.KeyChar <> ControlChars.Back Then
                    e.Handled = True
                End If
End Function

但它似乎没有用,有人可以告诉我通过这个功能的正确方法

1 个答案:

答案 0 :(得分:1)

你应该将它声明为Sub,因为它不会返回任何值并修改传入的参数。

Private Sub Numbers_Only(e As System.Windows.Forms.KeyPressEventArgs)
    If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso e.KeyChar <> ControlChars.Back Then
        e.Handled = True
    End If
End Sub

或者将其作为一种功能:

Private Sub Form1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    e.Handled = Numbers_only(e.KeyCode)
End Sub

Private Function Numbers_only(keyChar As System.Windows.Forms.Keys) As Boolean
    Return (keyChar < System.Windows.Forms.Keys.D0 OrElse keyChar > System.Windows.Forms.Keys.D9) AndAlso keyChar <> System.Windows.Forms.Keys.Back
End Function