Title: Check text data type in C#
This example shows how to use the TryParse method to check text data type. 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 int.
// 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 TextBox controls are similar. They just use other data types instead of int.
Download the example to experiment with it and to see additional details.
|