BLOG.CSHARPHELPER.COM: Determine whether a text value matches a particular data type in C#
Determine whether a text value matches a particular data type in C#
Each data type (int, float, bool, etc.) has a TryParse method attempts to parse a string and returns true if it is successful. You can use this to determine whether a textbox contains a valid value.
The following code shows how the program determines whether the value entered in the first textbox contains a valid integer.
// See if the text is an int. private void txtInteger_TextChanged(object sender, EventArgs e) { int value; if (int.TryParse(txtInteger.Text, out value)) { txtInteger.BackColor = Color.White; } else { txtInteger.BackColor = Color.Yellow; } }
The code declares the variable value. It then calls TryParse to attempt to parse the text in txtInteger. The code gives the textbox a white or yellow background depending on whether TryParse returns true or false.
The event handlers for the other textboxes are similar. They just use other data types instead of int.
Comments