David David - 5 months ago 21
Vb.net Question

vb.net Chr KeyPress function

When validating textboxes in vb.net, I usually use the .Chr or .ChrW function to define the valid ranges of ASCII values that can be entered. Today I came across something I've not had to do before, where I had to use this function in the

e.KeyChar <> Chr(156)
format, but replace the value 156 with the value for the GBP sign, or £

However, after finding out online via ASCII tables that the ASCII value is 156, I ran the code, and it wouldn't let me enter a £. What is the fix for this? Is there something I'm missing?

Private Sub txtFVal_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtFVal.KeyPress

If e.KeyChar <> Chr(156) AndAlso e.KeyChar <> Chr(46) AndAlso e.KeyChar <> Chr(44) AndAlso e.KeyChar = ChrW(Keys.Oemcomma) _
AndAlso (e.KeyChar < Chr(48) OrElse e.KeyChar > Chr(57)) AndAlso e.KeyChar <> Chr(8) Then
e.Handled = True
End If

End Sub


Instead of having to lookup its ASCII number just specify the char itself by suffixing a string with c - which in VB.NET indicates that you've specified a char literal:

If e.KeyChar <> "£"c AndAlso ...


Here's a more clean If-statement, see if it works:

If Char.IsNumber(e.KeyChar) = False AndAlso e.KeyChar <> "£"c AndAlso e.KeyChar <> ","c AndAlso e.KeyChar <> "."c AndAlso e.KeyChar <> Chr(8) Then
    e.Handled = True
End If