# VBForums CodeBank > CodeBank - Visual Basic .NET >  Restrict TextBox to only certain characters, numeric or symbolic

## Vectris

The following are some coding examples on how to customize which characters you want to keep from being entered into a TextBox.

To specify which characters are the *only* ones that are allowed to be in the TextBox:

(In this example only letters and numbers will be accepted into the textbox)


```
Public Class MainForm

    Dim charactersAllowed As String = " abcdefghijklmnopqrstuvwxyz1234567890"

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        Dim theText As String = TextBox1.Text
        Dim Letter As String
        Dim SelectionIndex As Integer = TextBox1.SelectionStart
        Dim Change As Integer

        For x As Integer = 0 To TextBox1.Text.Length - 1
            Letter = TextBox1.Text.Substring(x, 1)
            If charactersAllowed.Contains(Letter) = False Then
                theText = theText.Replace(Letter, String.Empty)
                Change = 1
            End If
        Next

        TextBox1.Text = theText
        TextBox1.Select(SelectionIndex - Change, 0)
    End Sub

End Class
```


To specify which characters *can not* be entered into the textbox:

(In this example any numbers will not be accepted into the textbox)


```
Public Class MainForm

    Dim charactersDisallowed As String = "1234567890"

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        Dim theText As String = TextBox1.Text
        Dim Letter As String
        Dim SelectionIndex As Integer = TextBox1.SelectionStart
        Dim Change As Integer

        For x As Integer = 0 To TextBox1.Text.Length - 1
            Letter = TextBox1.Text.Substring(x, 1)
            If charactersDisallowed.Contains(Letter) Then
                theText = theText.Replace(Letter, String.Empty)
                Change = 1
            End If
        Next

        TextBox1.Text = theText
        TextBox1.Select(SelectionIndex - Change, 0)
    End Sub

End Class
```

The above codes will also prevent copying and pasting from bringing unwanted characters.

----------


## edgarbenilde

thanks Vectris Good example...

----------


## danasegarane

> The following are some coding examples on how to customize which characters you want to keep from being entered into a TextBox.
> 
> To specify which characters are the *only* ones that are allowed to be in the TextBox:
> 
> (In this example only letters and numbers will be accepted into the textbox)
> 
> 
> ```
> Public Class MainForm
> ...




I think the loop can be avoid using this method



```
 Dim charactersAllowed As String = " abcdefghijklmnopqrstuvwxyz1234567890"
        Dim mystr As String = "asdf"
        If mystr.IndexOfAny(charactersAllowed.ToCharArray) > 1 Then

        End If
```

----------


## gooden

vb Code:
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged        Dim theText As String = TextBox1.Text        Dim Letter As String        Dim sel_s As Integer = TextBox1.SelectionStart        Dim did_change As Boolean = False        For x As Integer = 0 To TextBox1.Text.Length - 1            Letter = TextBox1.Text.Substring(x, 1)            If charactersAllowed.Contains(Letter) = False Then                theText = theText.Replace(Letter, String.Empty)                did_change = True            End If        Next        TextBox1.Text = theText        If did_change = False Then            TextBox1.Select(sel_s, 0)        Else            TextBox1.Select(sel_s - 1, 0)        End If    End Sub

I Did some changes so the selected does not change or jump.

----------


## Vectris

> I think the loop can be avoid using this method
> 
> 
> 
> ```
>  Dim charactersAllowed As String = " abcdefghijklmnopqrstuvwxyz1234567890"
>         Dim mystr As String = "asdf"
>         If mystr.IndexOfAny(charactersAllowed.ToCharArray) > 1 Then
> 
> ...


And then how are you going to get rid of any letters not in charactersAllowed?

Look at it the other way, if you use charactersDisallowed like that. How are you going to know which character is the disallowed one? You'll either end up looping through the characters in the text or the characters in the disallowedArray.

@gooden

I was to lazy to add something like that at the time, thanks for the suggestion :Alien Frog: . I added selection point saving in my own way (slightly shorter, skips the if statement).

----------


## daved2424

Is there a way to do this in VS 2003? The function contains doesn't work.

----------


## Vectris

> Is there a way to do this in VS 2003? The function contains doesn't work.


Sorry for not responding to this in a timely manner but for the sake of answering the question I've decided to respond.

I'm not exactly sure what commands VS 2003 does or doesn't support but if .Contains is the only problem check if you can use .IndexOf. If you can just replace the .Contains with .IndexOf and use = -1 for the second part of the condition instead of = False and <> -1 for True.

----------


## minitech

What about this?



```
Public Class MainForm

    Dim charactersAllowed() As Char = " abcdefghijklmnopqrstuvwxyz1234567890".ToCharArray()
    Dim lastText As String = String.Empty

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        If Me.TextBox1.Text.IndexOfAny(charactersAllowed) > -1 Then
                Me.TextBox1.Text = lastText
        Else
                lastText = Me.TextBox1.Text
        End If
    End Sub

End Class
```

----------


## Vectris

I think you meant that to be for charactersDISallowed but yes that works just fine. I'm not sure if there's a way to apply that method to charactersAllowed though. If there is go ahead and post your own codebank topic to it because textbox restrictions are a common question in the vb.net forums and it will make it a lot easier if you have a quick topic you can link them to.

----------


## minitech

Ah, OK.  :Smilie:

----------


## dlscott56

Just curious. Is there a reason not to use this method for allowed characters?



```
Private _allowedCharacters As String = "0123456789"

Private Sub UserIDText_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles UserIDText.KeyPress
     If Not _allowedCharacters.Contains(e.KeyChar) AndAlso e.KeyChar <> ChrW(Keys.Back) Then
         e.Handled = True
     End If
 End Sub
```

EDIT: Ahh, sorry just read this from the OP "The above codes will also prevent copying and pasting from bringing unwanted characters.". Where the KeyPress event won't handle it.

----------


## kayakerca

> The following are some coding examples on how to customize which characters you want to keep from being entered into a TextBox.
> 
> To specify which characters are the *only* ones that are allowed to be in the TextBox:
> 
> (In this example only letters and numbers will be accepted into the textbox)
> 
> 
> ```
> Public Class MainForm
> ...


Could this be modified to allow only one instance of a character?  In this case the "." so you couldn't enter a number with 2 "." if you were entering a double.

----------


## Edgar Avila

Module Main 
  Public DisallowedCharacters As String = "1234567890!#$%&/()=?¡¿\/*´'~`{}^@<>,;.:_¨|°¬+-""[]^¨"
End Module

  Private Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles TextBox1.TextChanged
        If TextBox1.Text <> Empty AndAlso TextBox1.Enabled Then
            If TextBox1.Text.IndexOfAny(DisallowedCharacters.ToCharArray) >= 0 Then
                Position = TextBox1.Text.IndexOfAny(DisallowedCharacters.ToCharArray)
                If Position = 0 Then
                    TextBox1.Text = Mid(TextBox1.Text, 2)
                Else
                    TextBox1.Text = Mid(TextBox1.Text, 1, Position) & Mid(TextBox1.Text, Position + 2)
                End If
                TextBox1.SelectionStart = Position
                Beep()
            End If
        End If
    End Sub

----------


## mark-totnes

I know this thread is old however I've just come across it with a Google search, so thought i'd post this if anybody else does...

I believe the simplest way to disallow characters is to use the Textbox.KeyPress event. 
The below snippet handles disallowed characters AND maximum number of lines if you have a Multiline Textbox:



```
    Private Sub txtAddress_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtAddress.KeyPress
        'Below Handles Disallowed Characters
        Dim DisallowedCharacters As String = "'~`{}^¨|°¬+-[]^¨"
        If InStr(DisallowedCharacters, e.KeyChar) > 0 Then
            e.Handled = True
        End If

        'Below Handles max number of lines for multiline Textbox
        If txtAddress.Lines.Length >= 6 AndAlso e.KeyChar = ControlChars.Cr Then
            e.Handled = True
        End If

    End Sub
```

----------


## intro

> I know this thread is old however I've just come across it with a Google search, so thought i'd post this if anybody else does...
> 
> I believe the simplest way to disallow characters is to use the Textbox.KeyPress event. 
> The below snippet handles disallowed characters AND maximum number of lines if you have a Multiline Textbox:
> 
> 
> 
> ```
>     Private Sub txtAddress_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtAddress.KeyPress
> ...



 Do you know how to update this to wear it uses 'IsNumeric'?

----------


## JuggaloBrotha

> Do you know how to update this to wear it uses 'IsNumeric'?


Why would you want to update this to use an old and outdated function?
For checking if something is numeric or not you would want to use Long.TryParse(), Decimal.TryParse(), or Double.TryParse() depending on how large of a number you're looking to check.  If it's simply 1 digit then Short.TryParse() would be sufficient.

I also see in this code example it uses InStr() for checking if the incoming character is in the dis-allowed list, the code could be modified to use DisallowedCharaters.Contains(e.KeyChar) instead.

----------

