If you're a fan of the old VB6 days one of the most useful functions was the IsNumeric function. Here is my version in C# and VB.NET (assuming you;re using .NET 4.0+):

C#

public bool IsNumeric(string Value)
{
    // Check for blanks
    if (string.IsNullOrWhiteSpace(Value)) {
        return false;
    }

    // Test for number
    double myNum = 0;
    return Double.TryParse(Value, out myNum);
}

VB.NET

Public Function IsNumeric(Value As String) As Boolean
    ' Check for blanks
    If String.IsNullOrWhiteSpace(Value) Then
        Return False
    End If

    ' Test for number
    Dim myNum As Double = 0
    Return [Double].TryParse(Value, myNum)
End Function

Bonus

You can easily change to validate specfic numeric types by changing the last two lines from Double to something line Int32:

C#

public bool IsInt(string Value)
{
    // Check for blanks
    if (string.IsNullOrWhiteSpace(Value))
    {
        return false;
    }

    // Test for number
    Inst32 myNum = 0;
    return Int32.TryParse(Value, out myNum);
}
Tags  |  C# |  VB.NET  |   |  Administrator