Parse user-entered values in C#
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 int.
// Parse an int.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 void txtInt_TextChanged(object sender, EventArgs e)
{
try
{
int value = int.Parse(txtInt.Text);
lblInt.Text = value.ToString();
}
catch
{
lblInt.Text = "Error";
}
}
// 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";
}
}


Comments