Strange problem with the minus(subtract) key

  • Thread starter Thread starter roidy
  • Start date Start date
R

roidy

I have a text box and I need to limit the input to just numbers, backspace
and the minus(subtract) key. I`ve set up a KeyPress event for the text box
and am using the following code:-

Private Sub textbox_KeyPress(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) _
Handles textbox.KeyPress

If Not Char.IsNumber(e.KeyChar) And _
Not e.KeyChar = Chr(Keys.Back) And _
Not e.KeyChar = Chr(Keys.Subtract) Then
e.Handled = True
End If
End Sub

This works perfectly for the number keys and the backspace key but not for
the minus(subtract) key. I can replace Keys.Subtract for any other key on
the keyboard and it works but I can`t get Keys.Subtract to work. Any ideas?

Thanks
Rob
 
This works perfectly for the number keys and the backspace key but not for
the minus(subtract) key. I can replace Keys.Subtract for any other key on
the keyboard and it works but I can`t get Keys.Subtract to work. Any
ideas?

Does this work as you expected:

If Not Char.IsNumber(e.KeyChar) AndAlso _
Not e.KeyChar = Chr(Keys.Back) AndAlso _
Not e.KeyChar = "-" Then
e.Handled = True
End If


-Teemu
 
That worked perfectly, it never occurred to me to just use "-", seems
strange that Keys.Subtract doesn't work through.

Thanks
Rob
 
roidy said:
That worked perfectly, it never occurred to me to just use "-", seems
strange that Keys.Subtract doesn't work through.

I'm not totally sure, but if I remember correctly, these Keys.Subtract,
Keys.Add and others should be used only in KeyDown and KeyUp events to look
up e.KeyCode.

KeyPress event returns just a character and KeyUp and KeyDown events return
a key code for example F-buttons and other special buttons.

-Teemu
 
Yep I just tested it and your right, but it seems kind of strange that
Keys.Back and most other keys can be used in a KeyPress event but not
Keys.Subtract. Oh well.

Rob
 
roidy said:
Yep I just tested it and your right, but it seems kind of strange that
Keys.Back and most other keys can be used in a KeyPress event but not
Keys.Subtract. Oh well.

Those Keys enumerations which have same integer as character's ASCII code
(letters, backspace and a few others) will "accidentally" work although it
is much easier to use for example "h" or "&" in KeyPress event.

-Teemu
 
Back
Top