Allowing/Restricting Certain Characters/Letters/Numbers in a Textbox

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (9 votes, average: 4.00 out of 5)
 

There are times where you may want to limit the characters that a user can put in a textbox control in Visual Basic.NET and Visual Basic 2005 or VB 2008. For example, if the textbox is used for math based calculations, you may only want the user to have the ability to put in numbers or only numbers with a single decimal point. Fortunately it is very easy to do.

In case you might care, some of these codes are taken from my csTextboxX .NET Control located at my www.vbcodesource.com website. All of these codes should be added to the Textbox_Keypress event and work with ALL versions of Visual Basic.NET (Including 2008, 2010, and higher).

Note: This article goes over how to Allow Only Numbers in a Textbox control with a Single Decimal Point (.).  I might add other articles in the future with code snippets on how to restrict other chars(characters) and user input. I do have code snippets on this site on restricting/allowing specific characters as well if you simply/only want the source code and nothing else.


Remember to put these codes in the Textbox controls _KeyPress event.

<

pre class=””>

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) _
    Handles TextBox1.KeyPress

'There are a couple scenerios this code is looking for. One is checking for the Decimal period "."
'and whether it exists in the textbox already. The other is seeing if the keypress was a Number and
'Control based key.
  If e.KeyChar = "." Then

'If a value higher than -1 is returned, it means there IS a existing decimal point’
    If TextBox1.Text.IndexOf(".") > -1 Then

'This says that I already dealt with the _KeyPress event so do not do anything else with this event.
        e.Handled = True

    End If
'
'Remember you want numbers to get through and the Control keys like “Backspace”
  ElseIf Char.IsNumber(e.KeyChar) = False AndAlso Char.IsControl(e.KeyChar) = False Then

'This says that I already dealt with the _KeyPress event so do not do anything else with this event.
    e.Handled = True

  End If

End Sub

Now if you run those codes, the textbox “should” only allow Number based characters with a Single decimal point char.

While the article was made to be very basic, hopefully it will give you a simple start on restricting textbox input to certain/specific characters. The basics from the article should help with that. Anyways, Have Fun!

Jason

17 thoughts on “Allowing/Restricting Certain Characters/Letters/Numbers in a Textbox

  1. Tom

    What does the e.handles mean/do because Visual Studio 2008 doesn’t understand it and I need an alternative way to do it.
    Thanks

    Reply
  2. Jason Post author

    Tom, I just tried the codes in VB 08 and it worked perfectly fine. I’m not sure exactly what problem your having with it.

    Also, e.handles in the _keypress event tells the base class that it doesn’t need to deal with the textbox_keypress event at this time.

    So in other words using e.handles allows us to do our own textbox processing/handling without the normal textbox processing taking place.

    I’m not sure if I made sense or not 🙂

    Jason

    Reply
  3. Jason Post author

    ARun, it sounds like you have the code in the wrong Textbox Event.

    It needs to be in the: Textbox1_KeyPress event of the target textbox control.

    Jason

    Reply
  4. Jason Post author

    Jedar, the code in this post will only allow numbers…

    If Char.IsNumber(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then

    e.Handled = True

    End If

    Reply
  5. Lukan

    Hello All and thank you Jason

    Now I have a question that maybe you can help me out with
    If after a character lets say Double Quote ” I want no more characters how can I prevent it, before it it’s fine

    I modify your code to fit my specific need and this is what I got

            'There are a couple scenerios this code is looking for. One is checking for the Decimal period "." 
            'and whether it exists in the textbox already. The other is seeing if the keypress was a Number and 
            'Control based key. 
            If e.KeyChar = "'" Or e.KeyChar = " " Or e.KeyChar = "-" Or e.KeyChar = """" Or e.KeyChar = "/" Then
                'If a value higher than -1 is returned, it means there IS a existing decimal point’ 
                If Side1.Text.IndexOf("'") &gt; -1 And Side1.Text.IndexOf(" ") &gt; -1 And Side1.Text.IndexOf("-") &gt; -1 And Side1.Text.IndexOf("""") &gt; -1 And Side1.Text.IndexOf("/") &gt; -1 Then
                    'This says that I already dealt with the _KeyPress event so do not do anything else with this event. 
                    e.Handled = True
                End If
                'Remember you want numbers to get through and the Control keys like “Backspace” 
            ElseIf Char.IsNumber(e.KeyChar) = False AndAlso Char.IsControl(e.KeyChar) = False Then
                'This says that I already dealt with the _KeyPress event so do not do anything else with this event. 
                e.Handled = True
            End If
    

    Any help provided will be greatly appreciated

    Reply
  6. Jason Post author

    Hi, if I understand you correctly try the code below.

            'Put it in the Textbox_Keypress event.
            'This will not allow anymore text to be typed in the textbox if it contains a " character.
            'Put it in the Textbox_Keypress event.
            'This will not allow anymore text to be typed in the textbox if it contains a ” character.
    
            If TextBox1.Text.Contains(Chr(34)) Then
    
                e.Handled = True
    
            End If
    

    See if that does what you want.

    Reply
  7. Lukan

    Tanks for the prompt reply Jason it seems I was too quick in responding that I had modified the code and it was working.
    In fact what I want to accomplish is to only allow the user to insert measurements using the imperial system in Feet, Inches and fractions, in this form 12’-3 ½ “ and after the “ no more characters are allowed since inches marks the end of the text or measurement
    The code I placed on the comment before it’s not accomplishing what I was expecting it allows multiple spaces, quotes, double quotes and minus sign to be entered and the function I’m using to read the feet inches text string has this formatted as 12’-3 ½ “
    See there can only be one feet sign ‘Or quote one minus sign or separator one space between the inch and the fraction of an inch and of course the inch sign or double quotes.
    I hope I have explain myself a little better and if there is anything that you can help me out with I will forever be eternally great full to you.
    Ps. Thanks in advance

    Reply
  8. darkiostream

    for restricting textbox for numbers only is here:

    if isnumeric(text1.text) = true then
    'your codes here
    else
    msgbox("numbers only")
    end if
    

    for restricting textbox for letters only only is here:

    if isnumeric(text1.text) = false then
    'your codes here
    else
    msgbox("numbers not allowed only only")
    end if
    Reply

Leave a Reply