Skip to content

Numeric or not

Vijay Prabhu

Asked Feb 15, 2006, 9:31 PM EST2 answers
Share
LinkedInX
How to check a field ..whether is it numberic or not. in Visaul Stdio2005 C#

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    Just make a function to check the field numeric or not. Something like the following: protected bool IsNumeric(string s) { try { Int32.Parse(s); } catch { return false; } return true; } Then use the function : if IsNumeric(textBox1.Text) { //write your code }
    0
  • 0
    There is no IsNumeric() function in C#.  It is VB only.  You will have to write your own method to code an equivalent, as suggested above.

    The following emulates the Val() function of VB.  It returns the numeric value of a string up to the first non-numeric character.  Otherwise it returns 0.  It works with positive or negative numbers and will accept a single decimal point.  However, you will probably prefer a bool method to emulate IsNumeric().

    C#
    public static double Valcs(string snum)
    {
    double vnum = 0; int N;
    snum = snum.Replace(" ", "");
    N = snum.Length;
    string[] anum = new string[N + 1];
    for (int x = 1; x <= N; x++)
    {
    anum[x] = snum.Substring(0, x);
    try
    {
    vnum = Convert.ToDouble(anum[x]);
    }
    catch
    {
    if(x != 0 && anum[x] != "-")
    break;
    }
    }
    return vnum;
    }
    0