Check text data type in C#

check text data type

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 Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in strings, variables and tagged , , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *