jamesG77296 jamesG77296 - 3 months ago 13
Vb.net Question

passing a function for validating numbers only vb.net

so i have this text field where i would like to only enter numberic values
i am able to do this with this piece of code

.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


the above code works fine but i am wondering if i can pass it as a function and call that function whenever i need it
somthing like so:

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


But it doesn't seem to work can somebody show me the correct way of passing this through the function please

Answer

You should declare this as a Sub as it doesn't return any value and modifies the arguments passed in.

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

Alternatively do it as a function:

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