Click here to Skip to main content
15,885,216 members
Articles / Programming Languages / C#

Validate numeric textbox using int.tryparse visual C#.NET

Rate me:
Please Sign up or sign in to vote.
3.67/5 (3 votes)
3 Oct 2011CPOL 99.8K   5  
Validate numeric textbox using int.tryparse visual C#.NET

Alternatives

Members may post updates or alternatives to this current article in order to show different approaches or add new features.

Please Sign up or sign in to vote.
15 Sep 2011ChunkyStool
The alternative posted by Daaron does not work for several cases. E.g. Sign is included (+ or -), text contains whitespace prefix or suffix, etc. You could fix the first two limitations with a more detailed regex like "(^\s*(-|\+)?\d+\s*$)" but you could still end up with a value that won't fit...
Please Sign up or sign in to vote.
2 Oct 2011endozs
You could always run the TryParse on the keyDown event so as to validate as the data gets entered. It saves the user an additional UI interaction. private void textBox1_KeyDown(object sender, KeyEventArgs e) { int i; string s = string.Empty; ...
Please Sign up or sign in to vote.
12 Sep 2011Daaron
You could do the same thing with a regular expression:if (Regex.Replace(textBox1.Text, @"\D", "") == textBox1.Text){textBox2.Text = ("tryparse method succeed");} else { textBox2.Text=("value entered is not numeric"); }
Please Sign up or sign in to vote.
23 Sep 2011Anshul R
using Microsoft.VisualBasic;// Codebool result = Information.IsNumeric("123");
Please Sign up or sign in to vote.
4 Oct 2011Horia Tudosie
See my article at Numeric Validator for Web Text Controls[^]
Please Sign up or sign in to vote.
5 Oct 2011wvd_vegt
Here is some old Delphi code that you could use to get more out of floating points strings before using TryParse().It will sanitize numbers like .25E4 or 10.E2 or -.24, all illegal in Double.TryParse.The code will also replace all non-floating point characters by a decimal separator (the...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions