Parse user-entered values in C#

example

You can use a data type’s Parse method to convert text entered by the user into a value with that data type. For example, the following code converts the text in the TextBox named txtInt into an int.

// Parse an int.
private void txtInt_TextChanged(object sender, EventArgs e)
{
    try
    {
        int value = int.Parse(txtInt.Text);
        lblInt.Text = value.ToString();
    }
    catch
    {
        lblInt.Text = "Error";
    }
}

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, by default decimal.Parse does not 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.

// Parse a decimal with any format.
private void txtDecimal2_TextChanged(object sender, EventArgs e)
{
    try
    {
        decimal value = decimal.Parse(
            txtDecimal2.Text, 
            System.Globalization.NumberStyles.Any);
        lblDecimal2.Text = value.ToString();
    }
    catch
    {
        lblDecimal2.Text = "Error";
    }
}


Download Example   Follow me on Twitter   RSS feed


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

One Response to Parse user-entered values in C#

  1. Pingback: Use TryParse to parse values entered by the user in C# -

Leave a Reply

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