Share via


Restrict TextBox to accept special characters

Question

Monday, December 22, 2008 10:42 AM

Hi,

I have a text box in my windows form which should only accept numeric values including (0-9) and (-,+) also. The text box should only restrict (A-Z) or (a-z) and special characters but not backspace, tab etc.
I tried using the following code under TextBox1_KeyPress event in different ways:

If (Char.IsLetter(e.KeyChar)) Then
    e.Handled = True
    MessageBox.Show("Letter not allowed")
End If

If Not Char.IsDigit(e.KeyChar) Then
    e.Handled = True
End If

If Not (Char.IsNumber(e.KeyChar)) Then
    MessageBox.Show("please enter a numerical value")
    e.Handled = True
End If

If (Char.IsSymbol(e.KeyChar)) Then
    e.Handled = True
End If

Also, tried to use the regular expression given below:

Dim reg1 As New Regex("@#$%^&*()=[\\];,./{}|:<>?")

If (reg.IsMatch(TextBox1.Text)) Then
    MessageBox.Show("Please enter the numbers only")
End If

I did not find any concrete solution. Although I got some result to restrict numeric value but unable to stop entering the special characters.

Any help is appriciated.

--Shubh

All replies (2)

Monday, December 22, 2008 12:26 PM âś…Answered

Hi,
The issue is fully resolved by doing some ammendment in code. The changes are done at the last validation in If statement. See below:

If Not (Char.IsNumber(e.KeyChar)) And e.KeyChar <> "-" And AscW(e.KeyChar) <> Keys.Back Then
e.Handled = True
End If

The issue is closed.

--Shubh


Monday, December 22, 2008 11:28 AM

Hi,

After a little more experiment, I could have solve the above given problem but still having problem to allow the "Backspace". Although I have written a condition but it seems not working.

The solution is given hereunder:

If Not (Char.IsNumber(e.KeyChar)) And e.KeyChar <> "-" And e.KeyChar.ToString() <> "\b" Then
e.Handled = True
End If

Note: The minus (-) character is also needed in textbox that's why the second condition is written.

The last condition is not helping me out. It would help me if anyone can assist in this.

--Shubh