How to identify if the entered data in text box is a string or a integer

I am making a small program for maintain the employee records with their ID numbers and their names. For this i have created two text boxes one for ID number, and another for the name. Now if the user enters a name in place of number and a number in place of a name in the relative textbox , i want the program to send a message back to the user to identify his error and to make the necessary corrections. How do i do that . Kindly help. This will make my program more accurate in its use.



Answer this question

How to identify if the entered data in text box is a string or a integer

  • George Waters

    The following will check for numeric entry and could be included in a button click event.

    If Not IsNumeric(TextBox1.Text) Then
    MessageBox.Show("Please enter a number")
    TextBox1.SelectAll()
    TextBox1.Select()
    End If

    Alternatively you can handle the textchanged event for the textbox and flag up an error as soon as the wrong key is pressed rather than wait until the box is completely entered, which could be more acceptable to your user.

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    If Not IsNumeric(TextBox1.Text) Then
    MessageBox.Show("Please enter a number")
    TextBox1.SelectAll()
    TextBox1.Select()
    End If
    End Sub

    The easiest way to check for correct name entry is just to assume that if the entry is not numeric it must be the name. However if you wanted to trap entries such as "ABC3" for instance you could handle the KeyPress event and check each character as it is entered. The following code will only allow letters and spaces to be entered.

    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    If Not Char.IsLetter(e.KeyChar) And Not e.KeyChar = " "c And Not e.KeyChar = Chr(Keys.Back) And Not e.KeyChar = Chr(Keys.Delete) Then
    e.Handled = True
    End If
    End Sub



  • GeorgeMohr

    Thanks Dave. I have tried your suggestion and i found it to be very helpful. Thanks a lot for the help.


  • How to identify if the entered data in text box is a string or a integer