Use TryParse to parse values entered by the user in C#

example

The example Parse user-entered values in C# explains how you can use a try catch block to protect against errors when parsing values entered by the user. For example, if the user types “ten” in a TextBox where you expect an integer, a try catch block can prevent the program from crashing.

Another approach is to use a data type’s TryParse method. Data types such as int, float, bool, and decimal all provide a TryParse method that takes as parameters the text to parse and an output variable to hold the result. The method sets the output variable to a default value (0 for the numeric data types) if it cannot parse the text. It returns true if it could parse the text and false if it could not.

The program uses the following code to parse a double value and a decimal value.

// Parse the values.
private void btnParse_Click(object sender, EventArgs e)
{
    double value;
    if (!double.TryParse(txtNumber.Text, out value)) value = -1;

    decimal currency;
    if (!decimal.TryParse(txtNumber.Text, NumberStyles.Any,
        null, out currency)) currency = -1;

    MessageBox.Show("Value: " + value.ToString() +
        "\nCurrency: " + currency.ToString());
}

The code first creates a double variable and uses TryParse to parse its value. If value isn’t a double, the code sets the value to -1.

Next the code parses a decimal value. It uses NumberStyles.Any and a null format provider to indicate that TryParse should be able to parse currency values in addition to other decimal formats.

The code finishes by displaying the results.

In the picture, the program failed to parse $1,234.56 as a double but succeeded in parsing it as a decimal value.


Download Example   Follow me on Twitter   RSS feed




This entry was posted in parsing, variables and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *