- Computers & Software»
- Computer Science & Programming»
- Programming Languages
Visual Basic TryParse Method
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,
- A variable holding the data type you wish to convert (a String in this example)
- The Variable type you want to convert or parse the original data type in to (an integer and double in this example)
- 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
'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
'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
This will allow you to exit the program!
Below is a list of controls for this example along with the properties changed for the program
- Text = "TryParse Example"
- Name = intTextBox
- Name = dblTextBox
- Name = intLabel
- Text = "Display Integer Here"
- Name = dbleLabel
- Text = "Display Double Here"
- Name = intButton
- Text = "Convert Integer"
- Name = dblButton
- Text = "Convert Double"
- 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
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
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.