Link to home
Start Free TrialLog in
Avatar of holemania
holemania

asked on

VB.Net - KeyPress Event

I have a textbox that I want to restrict to only numbers and commas.  I do not want the user able to type in a comma before they type in a number and the comma cannot be duplicate without a number separating it.

Example of what I want:

10,20,30,40,50,etc....

Cannot have the following:
10,,20,,30,40,etc.

I had been googling and was able to put this together, but I cannot tweak it where it would allow me to keep duplicate the comma but only after a number.

  Dim txt As TextBox = CType(sender, TextBox)
        If Asc(e.KeyChar) = 39 Then
            e.Handled = True
        End If

        If Asc(e.KeyChar) = 32 Then
            If txt.Text.Length = 0 Then
                e.Handled = True
            End If
        End If

        If Asc(e.KeyChar) = 44 Then
            If txt.Text.Contains(",") Then
                e.Handled = True
            End If
            If txt.Text.Length = 0 Then
                e.Handled = True
            End If
        End If

        If Asc(e.KeyChar) <> 44 And Asc(e.KeyChar) <> 8 Then
            If Asc(e.KeyChar) = 3 Or Asc(e.KeyChar) = 22 Then
                e.Handled = True
            End If
            If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
                e.Handled = True
            End If
        End If

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Eoin Ryan
Eoin Ryan
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
why not just use a NumericUpDown control?
User generated imageyou can set the ThousandsSeparator property if you want to include the comma.
also remember to set its Maximum, Minimum and DecimalPlaces properties when necessary.
Avatar of holemania
holemania

ASKER

Thanks for the recommendation.  Will have to play with boolean and see if it helps.

As for the suggestion using "NumericUpDown", this is a series or list separated by a comma per my list.  So the list can be 10, 20, 50, etc.  I just don't want where the user can type two or more commas consecutively without following by a number first.
Thanks.