How to limit data entry to numbers only in combobox

  • Thread starter Thread starter Tosch
  • Start date Start date
T

Tosch

I have a combobox where a user can select a zoom factor or enter a
zoom factor.
I tried to limit entry into the combobox to numbers only by catching
the keydown event and setting e.handled = true if any non number
characters are entered.
But those characters still appear in the combobox. Is this a combobox
bug?
If yes any workarounds?

Tosch
 
Hi Tosch,

Use the keypress event. The following worked fine for me, disallowing 'a':
If e.KeyChar = "a" Then

e.Handled = True

End If

HTH,

Bernie Yaeger
 
This is my code and it's not working. I want only numbers 0-9
accepted:

Private Sub ComboBox1_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress
Select Case e.KeyChar
Case "0" To "9"
Case Else
e.Handled = True
End Select
End Sub

BTW: I'm using VS2002.

Tosch
 
Tosch said:
This is my code and it's not working. I want only numbers 0-9
accepted:

Private Sub ComboBox1_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress
Select Case e.KeyChar
Case "0" To "9"
Case Else
e.Handled = True
End Select
End Sub

BTW: I'm using VS2002.

IIRC that's caused by the buggy implementation of the combobox.
 
Hi Tosch,

I tried your code inside vs 2003, which is all that I work with, and it
worked fine. So the answer has to be that there's a bug in 2002. Also, you
have to add a few characters - backspace, delete, arrow keys, etc. So you
may want to modify your code, into something like this:

Dim KeyAscii As Integer = Asc(e.KeyChar)
Select Case KeyAscii

Case 8, 27, 48 To 57, 9

Case Else

KeyAscii = 0

End Select

If KeyAscii = 0 Then

e.Handled = True

Else

e.Handled = False

End If


HTH,

Bernie Yaeger
 
Back
Top