Search code examples
.netvb.neteventskeypress

VB.Net check punctuation


i have a keypress event that limits the input to be only numbers like so:

Private Sub txtWeight_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtWeight.KeyPress

    If Not Char.IsNumber(e.KeyChar) Then
        e.Handled = True
    End If

End Sub

but i want to add the possibility to type periods too, so i tried to change the code to:

Private Sub txtWeight_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtWeight.KeyPress

    If Not Char.IsNumber(e.KeyChar) AndAlso Not Char.IsPunctuation(e.KeyChar) Then
        e.Handled = True
    End If

End Sub

But as you know the program lets me type every punctuation and i want to limit it to only "." how do i check what punctuation is being typed?


Solution

  • e.Handled = e.KeyChar <> "."c AndAlso Not Char.IsNumber(e.KeyChar)