Home » Programming / Coding

IsInteger in ASP .NET

19 May 2009 1,055 views No Comment

If you need to check if a number is an integer, there is no built in function for that in ASP .NET. But you can create a simple method for that like this (code shown in C#).

public static bool IsInteger(string inputValue)
{
if (!IsNumeric(inputValue))
return false;
try
{
int a = Convert.ToInt16(inputValue);    //Convert.ToInt16 will throw exception if string not integer
return true;
}
catch
{
return false;
}
}

public static bool IsNumeric(string inputValue)
{
if (string.Equals(“”, inputValue) || string.Equals(” “, inputValue))
{
return false;
}
else
{
/*
The surrounding ^ and $ characters mean that the expression must appear at the beginning and the end of the string. In real terms, this means that the expression must match the whole string – the string cannot contain any other characters.
*/
string strRegex = @”(^((\+|-)\d)?\d*$)|(^((\+|-)\d)?\d*(\.\d+)?$)”;

Regex re = new Regex(strRegex);
if (re.IsMatch(inputValue))
return (true);
else
return (false);
}
}

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.