[C# Helper]
Index Books FAQ Contact About Rod
[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]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

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

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

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