0

I am developing vb.net - windows application.

I have one text box in which, user supposed to enter data. I have put some validations like, user can put only numbers,alphabets and comma. ( No other symbols.) Its working fine, but I want to put restriction that only one comma should inserted not more than one.

How to do this ?

I have below code for key press event of text box.

 ReadOnly ValidChars As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,"

 Private Sub txtNewFlatName_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtNewFlatName.KeyPress
        Select Case e.KeyChar

            Case Convert.ToChar(Keys.Enter) ' Enter is pressed
                ' Call method here...

            Case Convert.ToChar(Keys.Back) ' Backspace is pressed
                e.Handled = False ' Delete the character

            Case Chr(22) ' CTRL+V is pressed
                ' Paste clipboard content only if contains valid characters
                e.Handled = If(Clipboard.GetText().All(Function(c) ValidChars.Contains(c)), False, True)


            Case Else ' Other key is pressed
                e.Handled = Not (ValidChars.IndexOf(e.KeyChar) > -1)


        End Select
    End Sub
Nilesh B
  • 121
  • 2
  • 2
  • 7

2 Answers2

0

In your Case Else, you could count the occurrences of "," in the text box using one of the methods described here:Count Occ of char in string or you could keep a flag on the class level and test if it is on (meaning that a ',' key was pressed) or not.

Community
  • 1
  • 1
NoChance
  • 5,632
  • 4
  • 31
  • 45
0

You will want to work from the KeyPress event...

Analyze whether or not the comma is pressed, if so...

then read the text box as a string...

use substring loop to read each character while counting the current number of , used...

If , is present, then supress the key from further entered..

Also, you might want to use a Beep() to tell them that's not acceptable...

Hope that helps..

Gale_i
  • 11
  • 3