[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: 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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.