locked
Wish to use text box to only allow numeric Data entry RRS feed

  • Question

  • I am creating a windows form with VB expressions

    How to I allow only text to be input into text box

    How do I allow only numeric data entered into textbox?

    How do I place a "zero" in the textbox if there is no value for the user to input?

    How do I allow for Currency?

    How do I place "," seperators and "$"?

    i.e     $ 1,123,123.00

    eg.

    Code: 'this is to create  liabilites calculator

    Dim mort. as double =textbox1.text

    Dim Credit as double =textbox2.text

    Dim Total as Double =Textbox3.text

    Total = Mort + Credit

    If i debug and do not place values in the box I get error. So I need to Have "0" by default.

     

    Thanks

    Chris

     

           

     

    Tuesday, January 24, 2006 5:52 PM

Answers

  • Here is a fairly straight-forward way to restrict your textbox to allow only numbers, $, and commas:

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

        Dim allowedChars As String = "0123456789$,"

        If allowedChars.IndexOf(e.KeyChar) = -1 Then
            ' Invalid Character
            e.Handled = True
        End If

    End Sub

    And here is how to restrict your textbox to a specific set of alphanumeric characters.  Note the e.KeyChar.ToLower so uppercase alpha characters don't need to specified in the allowedChars list.

    Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress

        Dim allowedChars As String = "abcdefghijklmnopqrstuvwxyz!@#$%&()-[]{}"

        If allowedChars.IndexOf(e.KeyChar.ToLower) = -1 Then
            ' Invalid Character
            e.Handled = True
        End If

    End Sub

    Tuesday, January 24, 2006 10:49 PM
  • *grin* Everyone was new once.  That's why people like me like to help newbies, we remember relying on help when we started.

    Add this code to your form class.

     

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

    Dim tb As TextBox = sender

    If Not (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar) Or (e.KeyChar = "." And tb.Text.IndexOf(".") < 0)) Then

    e.Handled = True

    End If

    If (tb.SelectionStart > tb.Text.Length - 2 And tb.Text.IndexOf(".") >= 0 And tb.Text.IndexOf(".") + 3 = tb.Text.Length) Then

    e.Handled = True

    End If

    If e.Handled = False And tb.Text.Length = 0 Then

    tb.Text = "$" + e.KeyChar

    e.Handled = True

    tb.SelectionStart = 2

    End If

    End Sub

    Private Sub TextKeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress

    If Not (Char.IsLetter(e.KeyChar) Or Char.IsControl(e.KeyChar)) Then e.Handled = True

    End Sub

    Private Sub NumericLeave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.Leave

    Dim tb As TextBox = sender

    If tb.Text.Length = 0 Then tb.Text = "$0.00"

    End Sub

    Now, go to the forms designer.  Click on a text box and on the bottom right, click the lightning flash to list events.  For the KeyPress event on a numeric text box, click in the box, then click the arrow and choose 'NumericKeyPress'.  For one to take only letters, choose 'TextKeyPress'.  For the numeric ones, also choose 'NumericLeave' for the leave event.  I think that does everything you want it to.  I encourage you to use MSDN to work through the code and learn how it all works.

     

    Tuesday, January 24, 2006 9:50 PM
  • hi,

    yes as what cgraus told you masked box is designed for thise cases but also you can do that through code but you will write much code like this

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

    ' textbox1 just accept numeric data

    If Char.IsNumber(e.KeyChar) Then

    e.Handled = False

    Else

    MessageBox.Show("plz click numbers only")

    e.Handled = True

    End If

    End Sub

    Private Sub TextBox1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Leave

    'format your entery during leaveing the textbox

    If TextBox1.Text = "" Then

    TextBox1.Text = "$ 0.00"

    Else

    TextBox1.Text = Format(Double.Parse(TextBox1.Text), "$ ###,###,##0.00")

    End If

    End Sub

    Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress

    ' textbox2 just accept letters

    If Char.IsLetter(e.KeyChar) Then

    e.Handled = False

    Else

    MessageBox.Show("plz click letters only")

    e.Handled = True

    End If

    End Sub

    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

    'validate textbox3

    Dim letters As Integer = 0

    Dim digits As Integer = 0

    Dim punctuators As Integer = 0

     

    For Each chr As Char In TextBox3.Text

    If Char.IsLetter(chr) Then

    letters += 1

    ElseIf Char.IsDigit(chr) Then

    digits += 1

    ElseIf Char.IsPunctuation(chr) Then

    punctuators += 1

    End If

    Next

    MessageBox.Show(String.Format("statistics of your entery {3} letters = {0}{3} digits = {1} {3} punctuators = {2}", letters, digits, punctuators, vbNewLine))

    End Sub

    hope that helps

    Tuesday, January 24, 2006 10:33 PM
  • You can use keypress event:

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

            If Asc(e.KeyChar) <> 13 AndAlso Asc(e.KeyChar) <> 8 _

            AndAlso Not IsNumeric(e.KeyChar) Then

                MessageBox.Show("Please enter numbers only")

                e.Handled = True

            End If

        End Sub


    Visual Basic 2008 Tutorials
    • Marked as answer by Chrisjune Friday, December 23, 2011 5:15 PM
    Friday, February 12, 2010 8:36 AM

All replies

  • How to I allow only text to be input into text box

    as opposed to what ?

    How do I allow only numeric data entered into textbox?

    handle the keypress event and then check if Char.IsNumeric, Char.IsControl and if you want decimals, if the char is a . and there is no . in the text already.  If this test failed, set e.Handled to true.

    http://www.dotnet247.com/247reference/msgs/26/134069.aspx

    This is one of many examples I found on the web

    How do I place a "zero" in the textbox if there is no value for the user to input?

    Handle the leave event, and if the string is empty, set it to "0"

    if textBox.Text.Length = 0 then textBox.Text = "0"

    something like that.

    How do I place "," seperators and "$"?

    Do you want them placed as you type ? That's a more complex control derived from a textbox.

    Actually, if you're using VB.NET 2005, then the masked edit control will do some or all of this.  Otherwise, if you're using an earlier version, see above :-)

    If i debug and do not place values in the box I get error. So I need to Have "0" by default

    Having a 0 is probably a nicer UI, but if you only want this because of this bug, then you should just write code to check if the textbox is empty, and act accordingly.

    Tuesday, January 24, 2006 7:49 PM
  • Ok, Forgive me for being "NEW" lol

    I want to "validate" I think the values of my many textbox's as either having "letter characters" or having "numeric characters" In some boxs I only want the user to only put in "numbers" elsewhere on the form I want them to just input "letters" such as thier name.

    How can I get my text boxes to except only "letter Characters" and others to accept only "number Characters"?

    For the text boxes that have only "numbers" in them if there is no value for them to input I want it to be "0" by default.

    Also am I correct that I can use a masked textbox to show "$" infront of all "number"?

    Thanks.

    chris

    Tuesday, January 24, 2006 9:15 PM
  • *grin* Everyone was new once.  That's why people like me like to help newbies, we remember relying on help when we started.

    Add this code to your form class.

     

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

    Dim tb As TextBox = sender

    If Not (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar) Or (e.KeyChar = "." And tb.Text.IndexOf(".") < 0)) Then

    e.Handled = True

    End If

    If (tb.SelectionStart > tb.Text.Length - 2 And tb.Text.IndexOf(".") >= 0 And tb.Text.IndexOf(".") + 3 = tb.Text.Length) Then

    e.Handled = True

    End If

    If e.Handled = False And tb.Text.Length = 0 Then

    tb.Text = "$" + e.KeyChar

    e.Handled = True

    tb.SelectionStart = 2

    End If

    End Sub

    Private Sub TextKeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress

    If Not (Char.IsLetter(e.KeyChar) Or Char.IsControl(e.KeyChar)) Then e.Handled = True

    End Sub

    Private Sub NumericLeave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.Leave

    Dim tb As TextBox = sender

    If tb.Text.Length = 0 Then tb.Text = "$0.00"

    End Sub

    Now, go to the forms designer.  Click on a text box and on the bottom right, click the lightning flash to list events.  For the KeyPress event on a numeric text box, click in the box, then click the arrow and choose 'NumericKeyPress'.  For one to take only letters, choose 'TextKeyPress'.  For the numeric ones, also choose 'NumericLeave' for the leave event.  I think that does everything you want it to.  I encourage you to use MSDN to work through the code and learn how it all works.

     

    Tuesday, January 24, 2006 9:50 PM
  • AHHH< Whats a Form Class and how do I get there?

    Sorry!!!!
    Tuesday, January 24, 2006 9:59 PM
  • First of all, you need to buy a book on VB.NET.  I am *not* being rude, everyone has to learn sometime, but you're going to find it difficult to continue without a basic foundation that you're more likely to get from a book than from the web.

    A form is another name for a window.  The main window which contains your textboxes has code behind it.  If you right click on the form in the design view and choose 'view code', you will see the code.  Just place this code inside the class ( i.e. not at the bottom, which would be outside the class, but under another method that is already there ).

    Then you can add the event handlers to call this code in your design view.

     

    Tuesday, January 24, 2006 10:08 PM
  • Didnt Take it as Rude!!! Thanks you for your help. I understand some of it but many of the terms are "NEW"
    You have been very helpfull and I appreciated  it .

    Chris
    Tuesday, January 24, 2006 10:12 PM
  • My pleasure.  I'm a moderator, so I've done it for you, but in future please try to mark an answer as correct when you've got the right answer in these forums.  The forums are searched for the VS help, and marking answers as right bumps their priority in the search :-)

     

    Tuesday, January 24, 2006 10:19 PM
  • hi,

    yes as what cgraus told you masked box is designed for thise cases but also you can do that through code but you will write much code like this

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

    ' textbox1 just accept numeric data

    If Char.IsNumber(e.KeyChar) Then

    e.Handled = False

    Else

    MessageBox.Show("plz click numbers only")

    e.Handled = True

    End If

    End Sub

    Private Sub TextBox1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Leave

    'format your entery during leaveing the textbox

    If TextBox1.Text = "" Then

    TextBox1.Text = "$ 0.00"

    Else

    TextBox1.Text = Format(Double.Parse(TextBox1.Text), "$ ###,###,##0.00")

    End If

    End Sub

    Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress

    ' textbox2 just accept letters

    If Char.IsLetter(e.KeyChar) Then

    e.Handled = False

    Else

    MessageBox.Show("plz click letters only")

    e.Handled = True

    End If

    End Sub

    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

    'validate textbox3

    Dim letters As Integer = 0

    Dim digits As Integer = 0

    Dim punctuators As Integer = 0

     

    For Each chr As Char In TextBox3.Text

    If Char.IsLetter(chr) Then

    letters += 1

    ElseIf Char.IsDigit(chr) Then

    digits += 1

    ElseIf Char.IsPunctuation(chr) Then

    punctuators += 1

    End If

    Next

    MessageBox.Show(String.Format("statistics of your entery {3} letters = {0}{3} digits = {1} {3} punctuators = {2}", letters, digits, punctuators, vbNewLine))

    End Sub

    hope that helps

    Tuesday, January 24, 2006 10:33 PM
  • Here is a fairly straight-forward way to restrict your textbox to allow only numbers, $, and commas:

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

        Dim allowedChars As String = "0123456789$,"

        If allowedChars.IndexOf(e.KeyChar) = -1 Then
            ' Invalid Character
            e.Handled = True
        End If

    End Sub

    And here is how to restrict your textbox to a specific set of alphanumeric characters.  Note the e.KeyChar.ToLower so uppercase alpha characters don't need to specified in the allowedChars list.

    Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress

        Dim allowedChars As String = "abcdefghijklmnopqrstuvwxyz!@#$%&()-[]{}"

        If allowedChars.IndexOf(e.KeyChar.ToLower) = -1 Then
            ' Invalid Character
            e.Handled = True
        End If

    End Sub

    Tuesday, January 24, 2006 10:49 PM
  • But this will allow a numeric value of

    459.3$.34

    I guess this allows you to be more explicit as to what chars to allow than char.IsXXX does, though.

     

    Tuesday, January 24, 2006 10:52 PM
  • I know I am still new but!!!

     

    I noticed that with the first posted Code I placed In the form class (see I am learning something) and that this was able to affect all textboxes! Mind you I noticed that if I were typing in code manually as apposed to copy paste this would have taken forever. It does give me what I need originally. However, the Masked Textbox's which I have set to numeric and numeric leave do not give me "$" nor "," as a seperator. A minor issue that I will play with.

    In the last posted code is it possible to handle all leave events with out re doing code for each box?

     Thanks for helping my learning curve everyone.

    Chris

    Wednesday, January 25, 2006 2:43 PM
  • Private Sub NumericKeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox10.KeyPress, TextBox11.KeyPress, TextBox12.KeyPress

           'This allows only numeric keypress.

    Dim tb As TextBox = sender

    Dim NChars As String = "1234567890"

    If NChars.IndexOf(e.KeyChar) = -1 Then

    ' Invalid Character

    e.Handled = True

    ElseIf e.Handled = False And tb.Text.Length = 0 Then

    tb.Text = "$" + e.KeyChar

    e.Handled = True

    tb.SelectionStart = 2

    End If

       How do I add "," as seperators for hundred, thousands, hundredthousands etc...? Other than allowing them as part of string?

    eg Dim Nchars As String = "1234567890,"

    Private Sub NumericLeave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox12.Leave, TextBox11.Leave, TextBox10.Leave

        ' This allows $0.00 if tabbed throw text box on Leave of textbox

    Dim tb As TextBox = sender

    If tb.Text.Length = 0 Then tb.Text = "$0.00"

    End Sub

    I am finding trouble with code to Place "$0.00" at load of application.

     

     

    Wednesday, January 25, 2006 3:46 PM
  • Also this code places "." and allows only two digits after the decimal point.

    If (tb.SelectionStart > tb.Text.Length - 2 And tb.Text.IndexOf(".") >= 0 And tb.Text.IndexOf(".") + 3 = tb.Text.Length) Then

    e.Handled = True

    End If

    Taken from first posted code. I placed it after

     "Dim NChars As String = "1234567890.,"

    from code above that I changed slightly from earlier help.

     

    Thanks again guys

    Wednesday, January 25, 2006 4:38 PM
  • Hello,

    I am having a problem taking this code and changing it to allow negative characters.

    Also, a newbie, so be gentle,

    Steph

    Monday, March 13, 2006 10:01 PM
  • Hello Experts

            I tried with the code sample and got tired

    Form2.cs(212): The best overloaded method match for 'char.IsDigit(char)' has some invalid arguments

    this was the error message shown to me

    the code was written like this

    if (

    !Char.IsDigit(e.KeyCode) && //not a number

    !Char.IsLetter(e.KeyCode) && //not a letter

    e.KeyCode.ToString() != "_" && //not an underscore

    !Char.IsControl(e.KeyCode) //not a delete, backspace, etc.

    )

    {MessageBox.Show ("hai");

     }

    whats is wrong in myself

    pls let me know


     

    Saturday, July 1, 2006 4:46 PM
  • Different approach:

    Public Class Form1

    Declare Function SetWindowLong Lib "user32" Alias _

    "SetWindowLongA" (ByVal hwnd As Integer, ByVal nIndex As Integer, _

    ByVal dwNewLong As Integer) As Integer

    Declare Function GetWindowLong Lib "user32" Alias _

    "GetWindowLongA" (ByVal hwnd As Integer, _

    ByVal nIndex As Integer) As Integer

    Sub NumericEdit(ByVal TheControl As Control)

    Const ES_NUMBER = &H2000&

    Const GWL_STYLE = (-16)

    Dim x As Integer

    Dim Estyle As Integer

    Estyle = GetWindowLong(TheControl.Handle, GWL_STYLE)

    Estyle = Estyle Or ES_NUMBER

    x = SetWindowLong(TheControl.Handle, GWL_STYLE, Estyle)

    End Sub

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    ' Name the textbox you want to be numeric only

    Call NumericEdit(TextBox1)

    End Sub

    End Class

    Sunday, July 2, 2006 1:53 AM
  • Hii,

    Well I can validate the textbox control to allow only numeric. But the problem that i am facing is, when i copy a string and paste in that text box control, it doesnt validate.

    I would appreciate your help if you can resolve this problem.

    Thanks

    --Jai

    Wednesday, September 27, 2006 8:10 PM
  • Wednesday, September 27, 2006 11:51 PM
  • hey, im new to vb 2005 and im basically creating a program that involves a student entering four of their modules and the program has to display their grades for them as well as the average. However, i having trouble writing the codes for adding all the numbers up and dividing them by 4 so i can get the average of all the grades.


    Can u give me a small example of how this would work?...please reply within 2 days if you can cause its due in 3 lol...take care...and if u do make it on time then send it to my email......moh0175@londonmet.ac.uk



    Thanks man

    Tuesday, March 6, 2007 12:04 AM
  • Hello,

             Thank U for this solution. This is nice solution. Tank U again.  But i don't understand this line can u help me to undersatand me ...please

     

     

    indexOf(e.KeyChar)= -1                 waht is  e ? . why u use indexOf     keyword ?                    

    Saturday, April 7, 2007 2:20 PM
  • Is there a way to code it so that it also allows you to use the back space key?

    Sunday, April 29, 2007 3:44 PM
  • i want to place the code (for accepting numeric only) in user control and want to use this user control to bind with data field like i have a data field with name 'qtypercarton' which is a numeric field when i bind this user control with data field initially it shows the value..but when i modify the value and exit from the user control which i placed on the form, it again shows me the previous value ..i tried every thing but all in vain.

     

    what i have done is made a user control and used public property procedure to return the value.

     

    when i debugged the user control i found that the returned value restores the old value..and is not updating when i modify the value from the user control which i placed in form 

    how can i come over this?

     

    regards,

    biju

     

    Tuesday, May 15, 2007 12:02 PM
  • The following code goes into the textbox KeyPress event. 

     

    The first line will allow only numeric entries.

    The second line will also permit the Backspace key to work.

    The third line will allow negative numbers to be entered, even if you cursor back to the beginning of the entry after a positive number is already there.

    The fourth line will allow a floating point number to be entered and restrict the input to only one dot.

    The fifth line allows you to press the Enter key to move the cursor to the next textbox.

     

     

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

    If e.KeyChar = Chr(8) Then e.Handled = False 'allow Backspace

    If e.KeyChar = "-" And TextBox1.SelectionStart = 0 Then e.Handled = False

    If e.KeyChar = "." And TextBox1.Text.IndexOf(".") = -1 Then e.Handled = False

    If e.KeyChar = Chr(13) Then TextBox2.Focus()

     

     

     

    Tuesday, May 15, 2007 5:38 PM
  • How do i do simple arithmic calculations in from text box on a windows form? Please help
    Saturday, July 14, 2007 1:27 AM
  • hey,
    are there anybody using MaskedTextBox for "numeric" purpose?

    Handling events like above with VS2005 seems to be a little bit primitive approach...

    Monday, November 26, 2007 12:16 PM
  • How can I validate my textbox which expects only numbers in WPF as there is no property called "Keychar" as that of Winforms.

     

    This code will allow the text box to expect only the numbers and backspace. The same dosent work in WPF.

     

    protected override void OnKeyPress(KeyPressEventArgs e)

    {

    if ((!char.IsDigit(e.KeyChar)) && (e.KeyChar != 8))

    e.Handled = true;

    }

     

     

    Could any help me in WPF validations?

    Thursday, June 5, 2008 7:27 AM
  • if (e.KeyChar == (char)Keys.Back | e.KeyChar == (char)Keys.Space|e.KeyChar==(char) Keys.Back)

    return;

    //e.KeyCode.ToString() != "_";

    if (char.IsLetterOrDigit(e.KeyChar))

    e.Handled = false;

    else

    e.Handled = true;

    //

    put this code in the textbox key press it will accpet only number , back space,and alphabets, it will not accpet any alphanumeric key.

    //

    Tuesday, November 11, 2008 10:40 AM
  • Someone was asking about validation when data is pasted into a textbox.  You can also ue the textchanged event to check the text.  You can't check the individual characters unless you loop through them but you can check it is numeric.

     

    Jeff - www.srsoft.us

     

    Tuesday, November 11, 2008 1:04 PM
  • I've just added some little things to cgraus' code remember it goes in the TexboxX.keypress event

    Dim tb As TextBox = sender
    
            If Not (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar) Or (e.KeyChar = "." And tb.Text.IndexOf(".") < 0)) Then
    
                e.Handled = True
    
            End If
    
            If (tb.SelectionStart > tb.Text.Length - 2 And tb.Text.IndexOf(".") >= 0 And tb.Text.IndexOf(".") + 3 = tb.Text.Length) Then
    
    
                e.Handled = True
                If e.KeyChar = Chr(8) Then e.Handled = False
            End If
    
            If e.Handled = False And tb.Text.Length = 0 And Not e.KeyChar = Chr(8) Then
    
                tb.Text = "$" + e.KeyChar
    
                e.Handled = True
    
                tb.SelectionStart = 2
    
            End If
    Now i am quite happy with the results but this approche would be much much better

    TextBox1.Text = Format( Double .Parse(TextBox1.Text), "$ ###,###,##0.00" )

    But there is way too many errors evolving this peace of code for example i can not write $1.50 it will amend it to $1.00 u get the idea.

     

    anyway this form helped me alot so thanks oh and yes i know this post is old lol





    Monday, November 23, 2009 8:33 PM
  • I didn't see anyone mention anything about the .tostring method's format string

    Can be handy as well

    Dim
    num As Double = CDbl(Me.txtNum.Text)
    txtNumText.Text = num.ToString(
    "C2")
    FREE DEVELOPER TOOLS, CODE & PROJECTS at www.srsoft.us Database Code Generator and Tutorial
    Tuesday, November 24, 2009 3:54 AM
  • You can use keypress event:

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

            If Asc(e.KeyChar) <> 13 AndAlso Asc(e.KeyChar) <> 8 _

            AndAlso Not IsNumeric(e.KeyChar) Then

                MessageBox.Show("Please enter numbers only")

                e.Handled = True

            End If

        End Sub


    Visual Basic 2008 Tutorials
    • Marked as answer by Chrisjune Friday, December 23, 2011 5:15 PM
    Friday, February 12, 2010 8:36 AM
  • how to use  backup of regedit
    Saturday, March 20, 2010 7:33 PM
  • how to use  backup of regedit
    Saturday, March 20, 2010 7:34 PM
  • Dude thanks, that is money.  So much better than writing code to show annoying errors to user.  Just don't let them enter wrong chars in the first place!  Excellent.
    Dan
    Friday, April 9, 2010 10:06 PM
  • u can use this code in ur app to allow back space including numbers

    paste this code in the keypress event of the text box

    Dim enteronlynumbers As String
            enteronlynumbers = "0123456789"
            If enteronlynumbers.IndexOf(e.KeyChar) = -1 Then
                e.Handled = True
            End If

    • Proposed as answer by mtp.karthik Wednesday, July 28, 2010 10:19 AM
    Wednesday, July 28, 2010 10:13 AM
  • I suspect the OP and the poster you are replying too have solved the problem by now.

    Look at the dates of the posts. :)


    Regards David R --------------------------------------------------------------- "Every program eventually becomes rococo, and then rubble." - Alan Perlis The only valid measurement of code quality: WTFs/minute.
    Wednesday, July 28, 2010 10:25 AM
  • hai...

    fantastic coding... Its working perfect..

    please do and follow this type coding...

    good..

     

    Wednesday, September 29, 2010 12:37 AM
  • Use the following code on keydown or press event:

    it works perfectly

                if ((e.Key < Key.D0) || (e.Key > Key.D9) & (e.Key < Key.NumPad0) || (e.Key > Key.NumPad9))
                {
                    e.Handled = true;
                    MessageBox.Show("Not a valid Number!");
                }

    Wednesday, September 29, 2010 6:19 AM
  • Here is a fairly straight-forward way to restrict your textbox to allow only numbers, $, and commas:

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

        Dim allowedChars As String = "0123456789$,"

        If allowedChars.IndexOf(e.KeyChar) = -1 Then
            ' Invalid Character
            e.Handled = True
        End If

    End Sub

    And here is how to restrict your textbox to a specific set of alphanumeric characters.  Note the e.KeyChar.ToLower so uppercase alpha characters don't need to specified in the allowedChars list.

    Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress

        Dim allowedChars As String = "abcdefghijklmnopqrstuvwxyz!@#$%&()-[]{}"

        If allowedChars.IndexOf(e.KeyChar.ToLower) = -1 Then
            ' Invalid Character
            e.Handled = True
        End If

    End Sub

    Hi Gordon, 

    I have one question, I used your code and when I pressed BACKSPACE it showed me an error..

    Please help

    Tuesday, December 28, 2010 7:17 PM
  • There is little point in addressing a post to someone who posted 5 years ago.

    However, as far as I can see there is no way that code can generate an exception if you press the BackSpace key.

    But it should be noted that there are better ways to achieve this than the methods posted in this thread; Solitaire's suggestion comes close but it doesn't handle pasting in text.  Try a search of the forum for other methods.

    Wednesday, December 29, 2010 12:00 AM
  • Thank you very much mtp.karthik your code worked 100% as am able to use backspace and space bar keys too

    only option is to copy and paste your code

    tried writing your code but i was unable to enter character for backspace key that is the "diamond character "   after number 9 in your code. i had to copy paste this character.

    Many Thanks again.

    Friday, January 14, 2011 7:04 AM
  • private void DubinPretrageTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
    {
    if ((e.Key != Key.Delete && e.Key != Key.Back && e.Key != Key.Left && e.Key != Key.Right) && ((e.Key < Key.D0) || (e.Key > Key.D9)) && ((e.Key < Key.NumPad0) || (e.Key > Key.NumPad9)))
    {
    e.Handled = true;
    MessageBox.Show("Not a valid Number!");
    }
    }
    Saturday, February 5, 2011 12:07 PM
  • I think you should try like this can help you

     

    Dim mort. as double =textbox1.text   to Dim mort. as double =val(textbox1.text)

    Dim Credit as double =textbox2.text  to Dim Credit as double =val(textbox2.text)

    Dim Total as Double =Textbox3.text  to Dim Total as Double =val(Textbox3.text)

     

    don't forget let me know about this if can help you.

    Friday, May 27, 2011 9:04 AM
  • You are right Cgraus....everyone was once new...but this seems to be one thing tht is easily forgetten....

    Keeps it up..friend....there is few like u on the milky way galaxy....believe me...very few...
    Sunday, August 7, 2011 4:43 AM
  • Help Please Respond ASAP!!! When I Run The Application/Program I Can't Use Backspace!!! how do I allow backspace!!!
    Friday, September 23, 2011 4:46 PM
  • The function ToLower doesn't work in my copy of VB2010. Replace

     If allowedChars.IndexOf(e.KeyChar.ToLower) = -1   with
    
    If(allowedChars.IndexOf(LCase(e.KeyChar))=-1 
    and it works.
    
    GordC
    
    


     

     


    • Edited by GordC Tuesday, September 27, 2011 9:36 PM
    Tuesday, September 27, 2011 8:34 PM
  • Hi,

    I am trying to do the same thing, I am using this code but I have about 8 number box's and it seems like a long winded way of doing this, does any body know a better way?

     

     

        Private Sub intrate_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles intrate.KeyUp
            If IsNumeric(intrate.Text) = False Then
                intrate.Text = ""
            End If
    
        End Sub

    Also it clears the box if a number then letter was typed!


    Thanks

     


    • Edited by drewjuk Thursday, October 6, 2011 10:57 AM
    Thursday, October 6, 2011 10:55 AM
  • Add a new class to your project with the following code:

    Public Class NumericTextBox
        Inherits TextBox
        Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs)
            Dim Point As Boolean
            If Me.Text.Contains(".") Then Point = True
            If Not (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar) Or (e.KeyChar = "." And Not Point) Or _
                (e.KeyChar = "-" And Me.SelectionStart = 0)) Then
                e.Handled = True
            End If
        End Sub
        Protected Overrides Sub OnTextChanged(ByVal e As System.EventArgs)
            If Not IsNumeric(Me.Text) And Text <> "-" And Text <> "." Then
                Text = ""
            End If
        End Sub
    End Class
    
    

    Build the project and a NumericTextBox will appear at the top of your toolbox.  Use it wherever you want a textbox which will only allow numeric entry.  No further code needed.

    • Proposed as answer by drewjuk Thursday, October 6, 2011 1:33 PM
    Thursday, October 6, 2011 1:00 PM
  • That worked brilliant thanks Dave you really are a VB GURU!! Legend!

    Does that mean I have to delete all my text fields and re add them as numericboxs?

     

    Thanks

    Thursday, October 6, 2011 1:33 PM
  • You could but then you'd lose all the handles clauses and have to go through and put them back in again.

    What you could do (carefully!!) is open up the Form.Designer.vb file (click on Show All Files in the Solution Explorer and expand the Form.vb node).

    Find the textbox declarations at the bottom of the file and replace "System.Windows.Forms.TextBox" with "NumericTextBox"

    Build the project.  This will then give you a few errors further up the file where the textboxes are instantiated which you will need to correct in the same way.

    Save the file and you're done.

    Thursday, October 6, 2011 2:13 PM
  • Excellent worked perfect, much better now stop the users putting in things they shouldn't!!
    Thursday, October 6, 2011 3:14 PM
  • Hi ,

    Great solution!! But how do I adapt this to also include scientific notation (ie 7e2). I've tried using the same syntax as with the "." but this does not work satisfactory.

    Thanks,

    A Malhotra

    Thursday, November 10, 2011 11:33 AM
  • visit this page posted by me.

    http://www.dotnetspider.com/resources/43435-Textbox-UserControl-New-properties-to-set-input.aspx

    You can use this control instead of usual textbox control everywhere. Whenever you require to restrict only numeric character set the "numonly" property and "declen" property accordingly

     

    numonly - for accepting only numeric input

    declen -  to restrict the decimal input to desired length of digits

     

     

     

     

     


    Ramanathan PowerBrain Software (India)


    Monday, December 26, 2011 6:31 PM
  • Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
            'Accept only numeric input
            Select Case Asc(e.KeyChar)
                Case 48 To 57
                    e.Handled = False
                Case 8
                    e.Handled = False
                Case 13
                    e.Handled = False
                Case Else
                    e.Handled = True
            End Select
    
        End Sub
    This is a great solution I always use.  If you need a character, just enter or include the ASCII integer value of the character to another 'Case' statement.  For , and $ you would add values 36 and 44.  Note: e.Handled (False allows, and True ignores)  Hope it helps anyone else out there.


    • Edited by ZOUL007 Thursday, July 26, 2012 6:23 PM spelling
    Thursday, July 26, 2012 6:20 PM
  • The following is an expansion of the above code.  It also permits negative numbers, a single decimal point, and scientific notation up to E+307.  (This is an updated version of the code previously posted and deleted.  There was no need for the Static Boolean variable.):

        Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
            'Accept only numeric input; decimal point and negative; scientific notation up to E+307
            Select Case Asc(e.KeyChar)
                Case 48 To 57       'numeric digits
                    e.Handled = False
                Case 8              'Backspace
                    e.Handled = False
                Case 13             'Enter key
                    e.Handled = False
                    If TextBox1.Text.Contains("E") Then  'Val converts to scientific notation
                        Try
                            TextBox1.Text = Val(TextBox1.Text).ToString
                        Catch
                            MessageBox.Show("Limit is E+307", "Unable to convert")
                            TextBox1.Clear()
                        End Try
                    End If
                Case 69, 101       'E or e used for scientific notation; only one permitted
                    If e.KeyChar = ChrW(101) Then e.KeyChar = ChrW(69) 'change e to E
                    If TextBox1.Text.Contains("E") Then
                        e.Handled = True
                    Else
                        e.Handled = False
                    End If
                Case 46             'single decimal point permitted
                    If TextBox1.Text.Contains(".") Then
                        e.Handled = True
                    Else
                        e.Handled = False
                    End If
                Case 45             'minus/negative sign permitted at start
                    If TextBox1.SelectionStart = 0 Then
                        e.Handled = False
                    Else
                        e.Handled = True
                    End If
                Case Else
                    e.Handled = True
            End Select
        End Sub


    Solitaire

    Saturday, July 28, 2012 1:29 AM