Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleParse user-entered values in Visual Basic .NET
DescriptionThis example shows how to parse user-entered values in Visual Basic .NET.
Keywordsparse, parse values, entered text, user-entered text, Visual Basic .NET, VB.NET
CategoriesStrings
 
You can use a data type's Parse method to convert text entered by the user into a value with the data type. For example, the following code converts the text in the txtInt textbox into an Integer.
 
Private Sub txtInt_TextChanged(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    txtInt.TextChanged
    Try
        Dim value As Integer = Integer.Parse(txtInt.Text)
        lblInt.Text = value.ToString()
    Catch
        lblInt.Text = "Error"
    End Try
End Sub
 
Note that the code uses a "try catch" block to protect itself from user errors. You should always use error handling when parsing user-entered values.

This technique works reasonably well for most data types but there is one catch for currency values. Normally programs store currency values in the Decimal data type because it has the right amount of precision. However, Decimal.Parse does not automatically recognize currency formats. For example, it gets confused if the user enters $12.34. That sometimes makes programs look odd because they can easily display currency values but cannot read them.

The solution is to pass a second parameter to Decimal.Parse that tells it to allow any recognizable numeric format.

 
Private Sub txtDecimal2_TextChanged(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    txtDecimal2.TextChanged
    Try
        Dim value As Decimal = Decimal.Parse( _
            txtDecimal2.Text, _
            System.Globalization.NumberStyles.Any)
        lblDecimal2.Text = value.ToString()
    Catch
        lblDecimal2.Text = "Error"
    End Try
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated