none
Integer.TryParse returning False

    Question

  • I am trying to work out why my code is not running correctly. 

    If Not Integer.TryParse(txtEmTel.Text, intTest) Or txtEmTel.TextLength <= 8 Then
                MsgBox("Telephone Number not valid! Please use between 8 & 11 digits")
    End If
    I am trying to test whether or not a text box input contains only numbers or not (designed for telephone number). intTest is declared as an Integer above, and I am trying to use Integer.TryParse to do this, but even if I type only numbers in to the text box, it still returns this MsgBox error message (should only display this if there are characters other than numbers input). Any ideas as to why this may be? Thanks in advance. 

    Wednesday, March 29, 2017 12:37 PM

Answers

  • If you're talking about ten digits then you're better off testing for Long (Int64):

    Private Function IsValidPhoneNumber(ByVal tb As TextBox) As Boolean

            Dim retVal As Boolean = False

            If tb IsNot Nothing Then
                If Not String.IsNullOrWhiteSpace(tb.Text) Then
                    If Long.TryParse(tb.Text, New Long) _
                        AndAlso tb.Text.Trim.Length = 10 Then
                        retVal = True
                    End If
                End If
            End If

            Return retVal

        End Function


    You might also want to look into using a MaskedTextBox.


    "A problem well stated is a problem half solved.” - Charles F. Kettering



    • Edited by Frank L. Smith Wednesday, March 29, 2017 1:28 PM ...modified code: Forgot to test the length
    • Proposed as answer by Cor LigthertMVP Wednesday, March 29, 2017 3:26 PM
    • Marked as answer by M477H3W Wednesday, March 29, 2017 3:32 PM
    Wednesday, March 29, 2017 12:49 PM

All replies

  • If you're talking about ten digits then you're better off testing for Long (Int64):

    Private Function IsValidPhoneNumber(ByVal tb As TextBox) As Boolean

            Dim retVal As Boolean = False

            If tb IsNot Nothing Then
                If Not String.IsNullOrWhiteSpace(tb.Text) Then
                    If Long.TryParse(tb.Text, New Long) _
                        AndAlso tb.Text.Trim.Length = 10 Then
                        retVal = True
                    End If
                End If
            End If

            Return retVal

        End Function


    You might also want to look into using a MaskedTextBox.


    "A problem well stated is a problem half solved.” - Charles F. Kettering



    • Edited by Frank L. Smith Wednesday, March 29, 2017 1:28 PM ...modified code: Forgot to test the length
    • Proposed as answer by Cor LigthertMVP Wednesday, March 29, 2017 3:26 PM
    • Marked as answer by M477H3W Wednesday, March 29, 2017 3:32 PM
    Wednesday, March 29, 2017 12:49 PM

  • If Not Integer.TryParse(txtEmTel.Text, intTest) Or txtEmTel.TextLength <= 8 Then
                MsgBox("Telephone Number not valid! Please use between 8 & 11 digits")
    End If
    I am trying to test whether or not a text box input contains only numbers or not (designed for telephone number). intTest is declared as an Integer above, and I am trying to use Integer.TryParse to do this, but even if I type only numbers in to the text box, it still returns this MsgBox error message


    Note that the max value of an Integer (Int32) is 2147483647 (214 748 3647)
    Numbers greater than that will fail Int32.TryParse or Integer.TryParse

    TryParse does a range check for the type.

    - Wayne



    Wednesday, March 29, 2017 1:21 PM

  • If Not Integer.TryParse(txtEmTel.Text, intTest) Or txtEmTel.TextLength <= 8 Then
                MsgBox("Telephone Number not valid! Please use between 8 & 11 digits")
    End If
    I am trying to test whether or not a text box input contains only numbers or not (designed for telephone number). intTest is declared as an Integer above, and I am trying to use Integer.TryParse to do this, but even if I type only numbers in to the text box, it still returns this MsgBox error message


    Note that the max value of an Integer (Int32) is 2147483647 (214 748 3647)
    Numbers greater than that will fail Int32.TryParse or Integer.TryParse

    TryParse does a range check for the type.

    - Wayne



    Hi

    Yes, there are a few other and better ways to input patterned text. My own preference is to use the TextBox key events to sort out what is required.


    Regards Les, Livingston, Scotland

    Wednesday, March 29, 2017 1:40 PM
  • Just use the MaskedTextBox control and set the Mask property for a phone number format:

    https://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.mask%28v=vs.110%29.aspx


    Paul ~~~~ Microsoft MVP (Visual Basic)

    • Proposed as answer by dbasnett Wednesday, March 29, 2017 2:49 PM
    Wednesday, March 29, 2017 2:23 PM
  • Just use the MaskedTextBox control and set the Mask property for a phone number format:

    https://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.mask%28v=vs.110%29.aspx


    Paul ~~~~ Microsoft MVP (Visual Basic)

    @Paul,

    Probably that goes in the USA but in many others countries that is impossible. 


    Success
    Cor

    Wednesday, March 29, 2017 3:25 PM
  • Hi everyone, thanks very much for your feedback. It was indeed a case of Integer not being long enough to hold the maximum 11 digits in a phone number. I have now changed this to Int64 and all is fine. Unfortunately I cannot mask the text box for a phone number format, as I am in UK and our phone number format is different to USA - (just 8-11 digits, no brackets or hyphens). But this I'm sure would be the best way to do it for US programs. 
    Wednesday, March 29, 2017 3:32 PM
  • Try this.  It will check for correct number of characters first, and then make sure each character is a digit.  Note:  You used <=8 which is incorrect, since it will not allow 8 characters.  It should be < 8.

    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim phonum As String, ln As Integer, nogood As Boolean
            phonum = TextBox1.Text
            ln = phonum.Length
            If ln < 8 Or ln > 11 Then
                MessageBox.Show("Number must be between 8 - 11 digits")
                TextBox1.Clear()
                nogood = True
            Else
                For Each car As Char In phonum
                    If Not Char.IsDigit(car) Then
                        nogood = True
                        MessageBox.Show("Number must include digits only")
                        TextBox1.Clear()
                        Exit For
                    End If
                Next
            End If
            If nogood = False Then
                MessageBox.Show("OK")
            End If
        End Sub
    End Class


    Solitaire

    Wednesday, March 29, 2017 4:36 PM
  • Just use the MaskedTextBox control and set the Mask property for a phone number format:

    https://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.mask%28v=vs.110%29.aspx


    Paul ~~~~ Microsoft MVP (Visual Basic)

    @Paul,

    Probably that goes in the USA but in many others countries that is impossible. 


    Success
    Cor


    In which case I would use Regular Expressions. There will be a feasible limit as to what can be validated with respect to a phone number if it's international (which was not mentioned).

    Paul ~~~~ Microsoft MVP (Visual Basic)

    Wednesday, March 29, 2017 5:55 PM
  • Paul, 

    Of course people who speak more languages wants to be able to call to the whole world. Not only my local numbers. 

    I don't know if you can read french, it is possible but I guess not. 

    Maybe can you make that Regex, I took this page because it is quite complete. If you cannot read French you can use the on most browsers available "translate to English". 

    https://fr.wikipedia.org/wiki/Numéro_de_téléphone

    :-)


    Success
    Cor

    Wednesday, March 29, 2017 6:08 PM
  • It was indeed a case of Integer not being long enough to hold the maximum 11 digits in a phone number. I have now changed this to Int64 and all is fine. . 

    Since you're using this to validate phone numbers, there's a marginal
    case you need to check for which will pass the TryParse test when it
    probably isn't desired: a leading plus or minus sign.

    The following strings are valid Integers or Longs, but may not match
    your criteria for a valid phone number:

    "-123456789"

    "+123456789"

    - Wayne

    Thursday, March 30, 2017 12:32 AM
  • I am confused as to why you are trying to parse a telephone number, as an integer, in the first place. You should be using the correct data type. A telephone number is not an integer, and even if you get this working correctly, it will likely cause problems in the future.

    I see you have already found a solution, because you've marked it as the answer, but I would highly suggest you use a different method, unless, there is some specific reason, as to why you need to convert a telephone number, to an integer. I cannot think of any.

    One way to do this, would be to use regular expressions. You can use a regular expression that will test phone numbers from different countries as well.

    Thursday, March 30, 2017 12:48 AM
  • I am confused as to why you are trying to parse a telephone number, as an integer, in the first place. You should be using the correct data type. A telephone number is not an integer, and even if you get this working correctly, it will likely cause problems in the future.

    I see you have already found a solution, because you've marked it as the answer, but I would highly suggest you use a different method, unless, there is some specific reason, as to why you need to convert a telephone number, to an integer. I cannot think of any.

    One way to do this, would be to use regular expressions. You can use a regular expression that will test phone numbers from different countries as well.

    I don't know if this causes the mistake by you, but many persons only read the last reply in a forum. The Op did not tell he/she tried to parse a telephone number in an integer. He/She wrote "test whether or not a text box input contains only numbers or not". It was just an easy way doing that, it failed because an integer is to small, but that did the OP admit after the reply from Frank and made an Int64 from it.

    Success
    Cor


    Thursday, March 30, 2017 2:58 PM
  • Cor,

    Do you not recognize the style of Mr. Alien?

    Think about it... ;-)


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Thursday, March 30, 2017 3:03 PM
  • Thanks all for your feedback, as I said, this case is now resolved after following advice from Frank L. Smith to change the integer to Int64, to allow for the length of the phone number. 

    WayneAKing, I take your point, but I only require this text field to contain national phone numbers, so a plus sign will never be required. Minus signs or hyphens never appear in national phone numbers anyway - they only consist of digits. 

    SpaceAlien2600 - Cor Ligthert is correct in saying that I am not trying to convert a phone number to an integer. You are correct that phone numbers are not integers, they are strings which is what textbox text is anyway, and I fully intend to store this phone number as a string. What I was trying to achieve was a "format check", to check that the phone number only contained digits 0 to 9. Whilst I understand there are other ways of doing this, trying to parse it as an integer just seemed like an easy way of doing this. 

    Anyway, thanks all for your feedback - this has really helped me. Please now consider the final answer to this thread to be the response marked as the answer, written by Frank L. Smith.

    Thursday, March 30, 2017 3:56 PM
  • WayneAKing, I take your point, but I only require this text field to contain national phone numbers, so a plus sign will never be required. Minus signs or hyphens never appear in national phone numbers anyway - they only consist of digits. 

    Huh?? I think you missed my point completely. Your purpose - I presume -
    in using TryParse is to ensure that the string contains only the digits
    0-9. No alpha, no special characters. But if someone *inadvertently* enters
    a + or - sign as the first character then TryParse will indicate it's OK
    when it isn't. You will have to check the first character as an additional
    test to ensure that it isn't + or - but only 0-9 since TryParse won't
    return False in such (remote) cases.

    - Wayne

    Thursday, March 30, 2017 6:20 PM
  • I am confused as to why you are trying to parse a telephone number, as an integer, in the first place. You should be using the correct data type. A telephone number is not an integer, and even if you get this working correctly, it will likely cause problems in the future.

    I see you have already found a solution, because you've marked it as the answer, but I would highly suggest you use a different method, unless, there is some specific reason, as to why you need to convert a telephone number, to an integer. I cannot think of any.

    One way to do this, would be to use regular expressions. You can use a regular expression that will test phone numbers from different countries as well.

    I don't know if this causes the mistake by you, but many persons only read the last reply in a forum. The Op did not tell he/she tried to parse a telephone number in an integer. He/She wrote "test whether or not a text box input contains only numbers or not". It was just an easy way doing that, it failed because an integer is to small, but that did the OP admit after the reply from Frank and made an Int64 from it.

    Success
    Cor


    I understand that, but the Integer.TryParse method only works on Integers, and a telephone number is not an Integer, so it shouldn't be used for that method. Even though it's "an easy way".

    The program should be properly developed. Using Integer.TryParse to test the contents of a String, is very poor programming practice, and will only cause problems in the future. We should practice appropriate programming methods when designing software.

    Thursday, March 30, 2017 9:08 PM
  • WayneAKing, I take your point, but I only require this text field to contain national phone numbers, so a plus sign will never be required. Minus signs or hyphens never appear in national phone numbers anyway - they only consist of digits. 

    @OP: You're completely missing the point that he was trying to explain to you... Your program is going to fail...
    Thursday, March 30, 2017 9:15 PM
  • I would agree with the others here. Your only inviting bugs into your program by coding this way.
    Thursday, March 30, 2017 9:18 PM
  • @M4777H3W

    I assume you're from the USA. Some of those speak if there is the USA (that is National) and the rest of the world. 

    Be aware next time when you use National. The language in this forum is US English. 

    However, the forums are meant for

    Finland
    Danmark
    Servia
    Croatia
    English speaking Canada
    The major part of Belgia
    The Netherlands
    The UK
    Suriname
    Jamaica and many West Indian countries
    Ireland
    India
    South Africa (and neighbour countries)
    Australia
    New Zealand
    And probably a lot more, 

    So when you speak about "National" it is a kind of discriminating a big part of the world and even larger countries than the USA. 

    Of course is TryParse likewise IsNumeric not such a good test for this, all numeric values even exponends fits and if it is about US phone numbers is using a regular expression better.
    But until now nobody told it was limited to US phone numbers (In my perception do US citizens as well call to Canada and Mexico and to more countries outside the USA, but in that I've of course not much experience). But you can make a wall around the USA that does not mean you can stop CO2 or persons calling others. And then is in my perception regular expression something for persons who we call her HillBillies. 

    The best way, try to get the phone book of the world and check if a number exist. (This is just a fake advice, you cannot buy that phone book). 

    What I would do was creating a numeric textbox for which are many replies given here. We've them on our website. But I don't even give you the link. The reply from Frank fits for most of the errors and the other are recognized simply when used. 

    @Frank, you think SpaceAlloien is the guy who always changed its nick and always told MVC was the way to go? You're right that he uses the same expressions. "We", I am sure that does not include me. 


    Success
    Cor



    Thursday, March 30, 2017 10:08 PM
  • Cor,

    I shouldn't have even speculated, honestly; but I do think we both know this person.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Thursday, March 30, 2017 10:16 PM
  • Why don't you guys focus on the problem at hand instead of getting off track and acting suspicious about a new member that just joined yesterday who was trying to help. This is how you welcome new members?

    Cor it says that you are an MVP? So I would stay out of the gossip. It is not professional, and you are supposed to be a most valued professional and Frank has 63,000 points yet you stoop to these levels and derail threads? I would expect more from these types of members.

    Also he is correct in his thinking. An integer should not be used to test a string. I only see that he was trying to help answer the question. He did nothing wrong.

    Thursday, March 30, 2017 10:23 PM
  • Thanks everyone for your continued support. 

    WayneAKing - Apologies for my misunderstanding. Thanks for letting me know about this, as I was not aware that a plus or minus sign could be stored as an integer. I'll add a bit in to ensure that plus or minus signs are removed before being saved to a file. 

    SpaceAlien2600 - I appreciate your feedback & that you are trying to help. However, at the end of the day this is my program and all I am trying to do here is get a working solution. If what I am trying to do is bad programming practice, then I'm sorry but that's tough - if it works, its fine. So far, I have not experienced any major issues using this simple method, so I will continue to use this method. 

    Cor Ligthert - Thanks for your detailed response as well. No I am from the UK and I only require UK phone numbers to be stored as is mentioned clearly in the above replies. Thanks for informing me about IsNumeric - this is something I will look in to using. 

    Thursday, March 30, 2017 10:27 PM
  • Since there is an answer and the thread has gone off the tracks I'm locking this thread down.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, March 30, 2017 10:27 PM
    Moderator

  • Cor it says that you are an MVP? So I would stay out of the gossip. It is not professional, and you are supposed to be a most valued professional and Frank has 63,000 points yet you stoop to these levels and derail threads? I would expect more from these types of members.


    Kenneth, 

    That Microsoft awarded me as an MVP, does not mean that I'm not a person. In past Frank asked me once  something like: "What does mean not professional." I did not respond, because I had no answer, my professional life in this business started somewhere at 1966. Am I an professional? Maybe, but beside that I agree with Frank. It does not give me any advantage above those who have a better non professional solutions. 

    I can write a lot more, but hope that you can understand what I want to say with those few words. I'm not one of those guys who think that more words makes a professional. 


    Success
    Cor

    Thursday, March 30, 2017 11:52 PM
  • SpaceAlien2600 - I appreciate your feedback & that you are trying to help. However, at the end of the day this is my program and all I am trying to do here is get a working solution. If what I am trying to do is bad programming practice, then I'm sorry but that's tough - if it works, its fine. So far, I have not experienced any major issues using this simple method, so I will continue to use this method.  

     "If it works, it's fine" is exactly the type of attitude that gets new programmers in trouble. If you don't want to take the advice of someone more experienced, then why post a question at all? And then you say that it's trough that you use bad programming practice when he is only trying to show you the correct way. Just because you have not experienced any major issues, does not mean that someone more experienced cannot see an unexpected flaw in your code, such as your not knowing about negative numbers being an integer... This is BASIC programming knowledge.

    @Cor: Please do not reopen a thread that was closed by a moderator, only to type further off-topic posts. Lets keep this professional?

     

    Friday, March 31, 2017 1:07 AM

  • @Cor: Please do not reopen a thread that was closed by a moderator, only to type further off-topic posts. Lets keep this professional?

     

    Then why are you responding to this?

    Maybe you call me an amateur, but what gives you the idea you have reached already the amateur stage. 

    We try to help each other, you have not add anything beside critique that the replies where wrong. Show how it could be done be better in an business responsible way. (which is the content of professional). 



    Success
    Cor





    Friday, March 31, 2017 1:16 AM
  • Hello to all involved with this thread, can we please refrain from personal attacks and keep on topic of the thread. As Frank and other frequent visitors to the forums here we tell you, we are all family and like any family there are disagreements. We had disagreements and now it's time to move on please.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Friday, March 31, 2017 1:16 AM
    Moderator
  • 800-THIS-FUNNY.  The OP early on had an answer that they accepted.  Several posts followed that expressed opinions about how to deal with phone numbers.

    There are a couple of standards from the ITU, E.123 and E.164, and hundreds of national formats that may or may not follow the standards. 

    Here is an opinion.  If the phone number satisfies the need of the intended audience then it is correct. 1-800-IS-THIS-OK? 

    How about 867-5309-JENNY


    "Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it." - MSDN User JohnWein    Multics - An OS ahead of its time.

    Friday, March 31, 2017 11:33 AM
  • Kenneth R. Jones - As I've said before, all I am looking for is a working solution - this does not need to be written 100% perfectly using all correct programming practices. The reason I posted the question in the first place was because I was not sure of the answer to my initial question, which was answered very soon on by Frank L. Smith, who informed me that Integer could not store 11 digits, which was the maximum required, and to use Int64 instead. I have taken this advice from Frank L. Smith who is more experienced than myself, and this has worked fine. 

    Of course, I will take all feedback from more experienced people who choose to help me post on this forum, as I appreciate the time that everyone has taken. You are correct that I am fairly new to programming, and I will act on as much feedback as I can. But, I cannot take every piece of feedback on board. Things like this, which people are only saying are incorrect because it is 'bad practice', and do not justify what problems it may cause are not something I will choose to pay attention to. Unless it can be justified why it is better than my intended solution, are not helpful. At the end of the day, it is still my program & only I know exactly what I want from it, so if there are certain things that people are wanting me to change without justifying why, then it is purely what THEY want, and it is tough that it will not be changed. 


    Friday, March 31, 2017 4:31 PM