In .NET, there is no builtin function available to check if the given value is a valid number or not. One option is to iterate through each character in the string and check if the given string contains all digits or not.
The following sample iterates through all characters and if all are digits return TRUE. If any character is not a digit, it returns false.
Note that the given sample doesn't consider 'period'. So, 12.25 will be invalid, according to the following samples. You may need to add additional validation to include the period and make sure there is no more than one period.
VB.NET sample :
Private Function ValidateNumber(ByVal input As String) As Boolean Dim c As Char For Each c In input If Not Char.IsNumber(c) Then Return False End If Next
Return True End Function
C# sample :
private bool ValidateNumber(string input ) { foreach ( char c in input ) { if ( ! Char.IsNumber( c ) ) { return false; } }
return true; }
Another inefficient, but easy method many programmers follow is,
Try Dim val As Int32 = TextBox1.Text Catch ex As InvalidCastException MessageBox.Show("Given value is not a valid 'Int'.") End Try
Try Dim val As Double = TextBox1.Text Catch ex As InvalidCastException MessageBox.Show("Given value is not a valid 'Double'.") End Try
The above method will work perfect to check any datatype, but depending on exception to check is not a reccommended approach.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|