TextBox only numbers (validation)

Hi, here I leave a very simple example to evaluate keystrokes when entering data into a textbox and only allow numbers ignoring everything that is not a number. It is basic but will serve as a starting point to validate any income. The following code ....

 TextBox1_KeyPress Private Sub (ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
 If (Not Char.IsNumber (e.KeyChar) And e.KeyChar <> Microsoft.VisualBasic.ChrW (8)) Then
 e.Handled = True
 End If
 End Sub

The char type has several properties that we would be very useful when performing validations. In the example we see the property. IsNumber ... Here some more to remember:

IsControl: Indicates whether the specified Unicode character is categorized as a control character

IsDigit: Indicates whether the specified Unicode character is categorized as a Decimal Digit

IsLetter: Indicates whether the specified Unicode character is categorized as an alphabetic character

IsLetterOrDigit: Indicates whether the specified Unicode character is categorized as an alphabetic character or a decimal digit

and many more ... I give you sound advice ... always consult the help.

34 Responses to "TextBox only numbers (validation)"

  1. Nino says:

    ehemp nnya leh .. gg!
    bwt klow parkir aplikasi, Masuk Harga menentukan give Harga keluarnya GMNA?
    kch sklian bzamah low contoh aplikasi parikir!
    hha ...!
    tolong pzn! ea ...!
    TWU low kirimin aku k e-mail ea!
    thank's!!

  2. Lena! Says:

    Hello

    You know I'm just getting started in vb and I'm being taught vn.net 2008, and I want to make a basic calculator such as complex but need not validate the texbox (only numbers) in the code that you expose me problem with the lt and that is not declared, then I guess I will gt problem, as stated to work.

    Thanks in advance ..

    • yagreor says:

      Look at the characters "<" and ">" are not VB. NET-HTML and should appear as "" respectively. INSTRUCTIONAL thus becomes:
      If (Not Char.IsNumber (e.KeyChar) And e.KeyChar Microsoft.VisualBasic.ChrW (8)) Then

      is that the question is old lady but I thought xD future visitors.

      • john says:

        hello, good

        Tabajo need to make a practical, and I have a textbox, and I have to validate if a number or text. For example if I have to enter your ID, I have to verify that it is number, and not how, if someone could help me, thank you very much.

    • Christian says:

      I hope you serve.

      You nuemros valid integer or decimal, you can tell how many decimal places to which you accept and will be the symbol of the decimal point or comma, depending on the country.

      Public Sub ValidaNumero (ByVal e As System.Windows.Forms.KeyPressEventArgs, _
      OText ByVal As TextBox, _
      Optional ByVal pbConPuntoDec As Boolean = True, _
      Optional ByVal pnNumDecimal As Integer = 2, _
      Optional ByVal psSimbolo As String = ".")
      As Integer Dim nDig
      Dim nCount, esDecimal, NumDecimales As Integer
      As Boolean Dim esDec
      Dim As String = String.Concat sTexto (oText.Text, e.KeyChar)
      If Asc (e.KeyChar) = Keys.Back Or Asc (e.KeyChar) = Keys.Return Then
      e.Handled = False
      Exit Sub
      End If
      Then if pbConPuntoDec
      If e.KeyChar.IsDigit (e.KeyChar) Or e.KeyChar = psSimbolo Then
      e.Handled = False
      E.KeyChar.IsControl ElseIf (e.KeyChar) Then
      e.Handled = False
      Else
      e.Handled = True
      End If
      nDig = sTexto.Length
      If nDig = 1 And Then e.KeyChar = psSimbolo
      e.Handled = True
      End If
      If oText.SelectedText "" Then
      Then if e.KeyChar = psSimbolo
      e.Handled = True
      End If
      Else
      If sTexto.IndexOf (psSimbolo)> = 0 And (nDig - (sTexto.IndexOf (psSimbolo) + 1))> Then pnNumDecimal
      e.Handled = True
      End If
      End If
      Else
      If e.KeyChar.IsDigit (e.KeyChar) Then
      e.Handled = False
      E.KeyChar.IsControl ElseIf (e.KeyChar) Then
      e.Handled = False
      Else
      e.Handled = True
      End If
      End If
      End Sub

  3. Hamlet Medina Sanchez says:

    Here I give you a code to validate only numbers not forget that it is in the keypress event of the textbox you will validate:
    Txt_Cantidad_KeyPress Private Sub (ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txt_Cantidad.KeyPress
    'Here we check if the pressed key is a letter if so then do not take or do not show the letter.
    If Char.IsLetter (e.KeyChar) Then
    e.Handled = True
    Else
    'Here you check if any key is pressed monitoring can be backspace, tabulardor, if so let it go you can delete standard pork.
    If Char.IsControl (e.KeyChar) Then
    e.Handled = False
    Else
    'Here you check if a separator or white space, if so do not let it go.
    If Char.IsSeparator (e.KeyChar) Then
    e.Handled = True
    Else
    'Check here if the key pressed is a number, so if you skip regular.
    If Char.IsDigit (e.KeyChar) Then
    e.Handled = False
    Else
    e.Handled = True
    End If
    End If
    End If
    End If
    End Sub

  4. Atillio (Roberto) Correa says:

    q x Finally someone deigns to make codes work as people q x over all things! thanks love saved me stress ... tqm!

  5. Ruben says:

    Good my friends a consultation, giving condigo enmodo console but if it works in web mode not know how to do it by fa ..... give me a hand

    Thx .............

  6. ALEX says:

    WANT TO KNOW HOW CAN VALIDATE THE MINUS SIGN AND THE DECIMAL POINT ... THANKS

  7. john says:

    hello, good night

    Tabajo need to make a practical, and I have a textbox, and I have to validate if a number or text. For example if I have to enter your ID, I have to verify that it is number, and not how, if someone could help me, thank you very much.

  8. Pam says:

    Kids this is definitely a blessing, I can not imagine that I would have been without this code
    MIL GRACIASSSSSS!!
    :)

  9. Edwin Rivas says:

    This is excellent, thanks friend.

  10. Miguel Angel says:

    This Ok.

    This code helped me a lot.

  11. Street says:

    cool ta

    chewere

  12. Sanclemente gino says:

    hi all .. very good code, I have served. q I would like to help me now and I'm working with a q q contains an object grid DataGridViewComboBoxColumn code i going to see if I help you find the error or q he needed:

    BtnAddRequisito_Click Private Sub (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnAddRequisito.Click
    Dim As String = Negocio.Conexion sConexion
    As New DataSet Dim Ds_datos
    As String Dim sQuery

    CboRequisitoColumn.Name = "Subject"
    Me.DGVMaterias.Columns.Add (CboRequisitoColumn)
    sQuery = "SELECT asg_codigo as code, description FROM asg_nombre as spsatbasignatura WHERE asg_semestre <" & Me.CMBSemestre.Text

    Ds_datos = Accesar_Datos.GetDataSet (sQuery, sConexion)
    my_DGVCboColumn.DataSource = Ds_datos.Tables (0)
    my_DGVCboColumn.Name = "Data"
    my_DGVCboColumn.DisplayMember = Ds_datos.Tables (0). Columns ("description"). ToString
    my_DGVCboColumn.ValueMember = Ds_datos.Tables (0). Columns ("number"). ToString

    Me.DGVMaterias.Columns.RemoveAt (0)
    Me.DGVMaterias.Columns.Insert (0, my_DGVCboColumn)
    End Sub

    'The former creates the grid
    'The following is where I want
    'Assign or insert the code gives me q
    'My_DGVCbocolumn object q is within q DGVMaterias xq I think I should not
    'Refer to CboRequisitoColumn

    Private Sub Agregar_Requisitos ()
    SQuery Dim As String = ""
    Dim As String = Negocio.Conexion sConexion
    As New DataSet Dim Ds_Datos
    KROW Dim As Integer = 0
    Dim aux As String
    Dim r As Integer

    Try

    For KROW = 0 To Me.DGVMaterias.RowCount - 1
    aux = Me.my_DGVCboColumn.Items (KROW). ToString
    r = CType (aux, Integer)
    sQuery = "spi_spsatbrequisito_asignatura" & Code & "" & r & ""
    Ds_Datos = Accesar_Datos.GetDataSet (sQuery, sConexion)
    Next KROW
    Catch ex As Exception
    MsgBox (ex.Message, MsgBoxStyle.Critical, "Error")
    End Try

    End Sub

    'Beforehand by

  13. sneyder rich says:

    hello, I would like to know how do to q in a single box to type in letters and no numbers.
    pd, I need to as soon as possible if it can be better today.
    thank you very much for your attention.

    • MACHM says:

      TextBox2_TextChanged Private Sub (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
      If IsNumeric (TextBox2.Text) Then
      MsgBox ("Must be letters")
      End If
      End Sub

      • Samuel says:

        Hey your code is not valid.
        Q Only show message saying not contain letters, but if you remove the message does naaa.

    • Kike says:

      e.hendled put the same and put the opposite .... if you change false to true and vice versa ....

  14. Lyn says:

    thank you very much! x I'm doing this blog I proje xq and no longer gives me the head if they could help me with this thank you:
    I have a form where income and other data with a grid where q is consulted but when I want to see from the first q I have saved the information in the grid fails naa naa I filter on the primary key but not <if they inspire me thank you

  15. frog says:

    as I can do to make a textbox then appears a legend when entering data in another textbox?? if someone could help me be grateful

  16. christian says:

    query as you can make when entering the numbers to texbox these points automatically put the thousands

    • Elisha says:

      you can format it using the LostFocus event:
      TextBox1.Text = Format (TextBox1.Text, "Fixed")
      for example.

  17. andres said:

    Please can you help me, I need to validate the entry of numbers into a text box, I have validated that supports only numbers, now I need to validate the entry of the first number that is only number 2.

  18. Sentinel says:

    know from there I found some code a bit complex to type text or numbers only, but if I bring a very simple code, and simplemte enough to change a single parameter to make the difference between accept text or numbers, well no more to say and Waiting sae them very useful here I go:

    first we refer to:

    Imports System.Windows.Forms.Form

    and then create a function that contrendra the master code to verify its contents as follows:

    KeyAscii As Short Public

    'Function to allow only numbers, period, comma, backspace and enter
    Tecla_Presionada Function (ByVal KeyAscii As Short) As Short
    If InStr ("0123456789.", Chr (KeyAscii)) = 0 Then (so only accept numbers, and what expliqye as above, but if we take "= 0" will only support the reverse points, I hope I understand but then I explain ...)
    Tecla_Presionada = 0
    Else
    Tecla_Presionada = KeyAscii
    End If
    Select Case KeyAscii
    Case 8
    Tecla_Presionada = KeyAscii
    Case 13
    Tecla_Presionada = KeyAscii
    End Select
    End Function

    Once the function we go to textbox1 so to speak you will know as it is known that if the KeyPress event and digitamos the following:

    TextBox1_KeyPress Private Sub (ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    Dim KeyAscii As Short = CShort (Asc (e.KeyChar))
    KeyAscii = CShort (Tecla_Presionada (KeyAscii))
    If KeyAscii = 0 Then
    e.Handled = True
    End If
    End Sub

    And we treat the program ready and that's it, that's all folks I hope is useful to them, until then, any questions comment ...

  19. Aleschka says:

    Very good and useful your post!
    nserio saved me!
    many graciass
    =)

  20. carlos says:

    To be perfect you just have to eat the digital control and automatic placement of thousands of points.

    Thanks

  21. Joseph says:

    hello I would like to help me q q a textbox I accept only letters and spaces
    I need it as soon as possible thanks

  22. Naty says:

    hello I will be able to help with the code to accept but I need to extract data from the Bd but not how porfis if they are the agradecede ...

  23. Andres says:

    hi I'm also starting to create a visual basic text editor visual basic, I have a question to ask in a RichTextBox when I write words for example. "Hello World" that I want white space to fill with * would remain so "Hello * world," but not what the function, I will not do it directly in the RichTextBox if that means a button as you finish typing give the text to the button click to call the function (if it is a function) and all the blanks in the RichTextBox fill me with * which is the source code or what is the function to do this and how would call the the function button (in case of a function). Indeed it is in Visual Basic 2008

  24. edwin says:

    This comment has been very helpful either m

Comment