ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Visual Basic TryParse Method

Updated on February 1, 2016

What Is A TryParse Method?

A TryParse method is typically used when you are attempting to convert one data type to another, the typical use I have personally come across is taking a user input from a text box and passing (converting) in to an integer or double.

When you use a TryParse method you typically need 3 things,

  1. A variable holding the data type you wish to convert (a String in this example)
  2. The Variable type you want to convert or parse the original data type in to (an integer and double in this example)
  3. A Boolean (True or False) to evaluate the outcome of the TryParse (this allows us to decide what we are going to do once it has Parsed.)

The typical layout for the TryParse Method is as follows (using both integer and double)

BooleanName = Integer.TryParse(StringName, IntegerName)

or for a Double

BooleanName = Double.TryParse (StringName, DoubleName)

As you can see with a basic understanding that when that line of code is executed the Boolean Value (either true or false) will be set according to the outcome of the TryParse execusion, if in both cases the data type stored in the string is correct, the Boolean will be set to True, if however the String data is not of the correct type then the Parse will fail and the Boolean will be set to False.


Setting Up Our Example Form

For our TryParse example we will need to set up a basic windows from within the Visual Basic IDE - (I have not added any tutorials on the IDE however if you would like me to do some please let me know)

The basic layout of the form is not that important in this example, however I do urge all new programmers to get in to the good habits of labeling controls to something meaning full and laying a from out propley

To your form add

  • 2 TextBox Controls (named (intTextBox & dbelTextBox))
  • 2 Label Controls (named (intLabel & dblLabel)
  • 3 Button Controls (named intButton & dblButton & closeButton)

The picture below shows the basic form layout I have used in order to demonstrate the use of both TryParse methods. A full list of what I have changed for each control/component can be found below in the Reference section

Once you have set up your form to complete this example move on to the Adding Code section to write your TryParse methods

TryParse Form Layout

The TryParse Example Explained & Code

In this example when the buttons are pushed we (Convert Integer or Convert Double) the program takes the value in the text box, it then attempts to convert them to either an Integer Value or a Double Value depending on which button is pushed. The Program then evaluates if that TryParse was successful or not, if it was it will display the value inside of the label and if the TryParse was not successful it will open a message box and give the user feedback.

Code Step 1 - Setting the Variables

View the code editor (right click on your form and select view code) and you will see Public Class Form1 displayed. under the Public Class Form1 we declare the following variables (Full code is in the picture below and a full code reference is at the bottom.

  • Dim ParseSuccessful as Boolean = False
  • Dim myIntString as String = ""
  • Dim myDblString as String = ""
  • Dim myInt as integer = 0
  • Dim myDbl as Double = 0

Code Step 2 - Write The Code For The Convert Integer Button

Double click the Convert Integer Button on your form so the IDE generates the button_click event handler and type the following code inside ensuring it is above the End Sub

'place the textbox data in a string
myIntString = intTextBox.Text

'attempt to parse data in to an integer
ParseSuccessful = Integer.TryParse(myIntString, myInt)

'evaluate the result
If ParseSuccessful = True Then
'if the parse was a success display the integer value in the label
intLabel.Text = myInt.ToString
Else
'if the parse failed display a message box explaining and clear the label and textbox
MsgBox("Please Enter a Numberical Value In The Integer Text Box")
intLabel.Text = ""
intTextBox.Text = ""

NOTE: All lines starting with ' are comments to explain, these lines will be green if you copied the code in to the IDE.

NOTE 2: You do not specifically need to add the textbox entry in to a string, but for ease of explination I have opted to do it this way.

That is now the code to handle the integer conversion, the notes should help explain what is going on, first take the value and store in a string, then attempt to convert the string in to an integer, if that is ok we display the integer in the label, else we alert the user and clear the fields.

Code Step 3 - Coding the Convert Double Button

To do this again double click on the Convert Double Button, and then type in the following code before the End Sub line

' place the textbox data in a string
myDblString = dbleTextBox.Text

'attempt to convert to a double *note the double.tryparse)
ParseSuccessful = Double.TryParse(myDblString, myDbl)

' if the parse is successful add the double to the label
If ParseSuccessful = True Then
dbleLabel.Text = myDbl.ToString
Else
'esle alert the user and clear the label and text box
MsgBox("Please only type numerical vales in the double box 1 . (period) is allowed")
dbleLabel.Text = ""
dbleTextBox.Text = ""

Code Step 4 - Code The Close Button

Double click on the close button and type in

Me.Close()

This will allow you to exit the program!

Control Reference

Below is a list of controls for this example along with the properties changed for the program

Main Form

  • Text = "TryParse Example"

TextBox1

  • Name = intTextBox

TextBox2

  • Name = dblTextBox

Label1

  • Name = intLabel
  • Text = "Display Integer Here"

Label2

  • Name = dbleLabel
  • Text = "Display Double Here"

Button1

  • Name = intButton
  • Text = "Convert Integer"

Button2

  • Name = dblButton
  • Text = "Convert Double"

Button3

  • Name = closeButton
  • Text = "Close App"

Note : You can label your controls as you wish however just remember to reference your names in your code so that it compiles correctly!

TryParse Example Code

Public Class Form1
    Dim ParseSuccessful As Boolean = False
    Dim myIntString As String = ""
    Dim myDblString As String = ""
    Dim myInt As Integer = 0
    Dim myDbl As Double = 0

    Private Sub intButton_Click(sender As Object, e As EventArgs) Handles intButton.Click
        'place the textbox data in a string
        myIntString = intTextBox.Text

        'attempt to parse data in to an integer
        ParseSuccessful = Integer.TryParse(myIntString, myInt)

        'evaluate the result
        If ParseSuccessful = True Then
            'if the parse was a success display the integer value in the label
            intLabel.Text = myInt.ToString
        Else
            'if the parse failed display a message box explaining and clear the label and textbox
            MsgBox("Please Enter a Numberical Value In The Integer Text Box")
            intLabel.Text = ""
            intTextBox.Text = ""
        End If

    End Sub

    Private Sub dbleButton_Click(sender As Object, e As EventArgs) Handles dblButton.Click
        ' place the textbox data in a string
        myDblString = dblTextBox.Text

        'attempt to convert to a double *note the double.tryparse)
        ParseSuccessful = Double.TryParse(myDblString, myDbl)

        ' if the parse is successful add the double to the label
        If ParseSuccessful = True Then
            dbleLabel.Text = myDbl.ToString
        Else
            'esle alert the user and clear the label and text box
            MsgBox("Please only type numerical vales in the double box 1 . (period) is allowed")
            dbleLabel.Text = ""
            dblTextBox.Text = ""
        End If
    End Sub

    Private Sub closeButton_Click(sender As Object, e As EventArgs) Handles closeButton.Click
        Me.Close()

    End Sub
End Class

Testing & Using Your App

Now we have completed our TryParse example click the Start Debugging button and run your application. You will see your new form displayed, below are some steps you can use to test your application is working as intended

Try 1

Simply push the Convert Integer button and the Convert Double button before putting any information in to the text boxes you should see that a message box appears and on closing the message box the label text is removed

Try 2

Type some random numbers and letters in the both of the text boxes, and then click on the Convert Double and Convert Integer buttons, due to the parse failing because there are letters or "non numerical" values in the text boxes you will get a message box and the text in the corresponding label will be removed and the text in the corresponding text box will be removed.

Try 3 - Integer

Type a number (numbers only no spaces of periods) in to the intTextBox - now click the Convert Integer you will see that because the TryParse was a success the value is now displayed in the intLabel!

Try 4 - Double

Type a number containing a . (period or full stop) in the dblTextBox and click the Convert Double button, due to the Double.TryParse being a success the value is placed inside the dblLabel.! (note: you can place just a number without a . in the dblTextBox and it will still work fine)


Completed TryParse Example

TryParse Example Conclusion

In this example we took 2 String values presented by the user and checked that they are of the correct data type in order to add them in to the numerical data types. These are just 2 types I use a lot in code and there are many other data types you can pass information between.

While as a stand alone project this doesn't have much value the code can be used within other applications in order to evaluate user input to parse in to an integer or double. You will see as time goes on this Hub is referenced to in many other code examples of mine that involve converting strings in to number data types.

If you like this example and wish me to write more please leave your comments below. I would also be interested in your ideas for tutorials. While this is basic I think going through a full list of examples rather than jumping in to harder code is good practice.

Feedback

Did you find the TryParse Example useful?

See results

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)