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.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.