How to limit data entry to numbers only in combobox

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
 
B

Bernie Yaeger

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
 
T

Tosch

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
 
C

Cor Ligthert

Tosch,

Tosch,

Some hours ago I showed this sample too EDB he told me that it was what he
wanted, however, that it can be optimized, and he is right, it where first
two samples.

http://groups.google.com/[email protected]

I did not change them yet.

I hope however that it helps you as well.

Cor
 
H

Herfried K. Wagner [MVP]

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.
 
B

Bernie Yaeger

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top