Start New Discussion within our Software Development Community

i have many textboxes in my form, now i want to validate the data inside it. how can i achieve this other than the try catch? i want the validation to be usable in all my forms so i'll write it as a sub/function. any suggestions?

i have many textboxes in my form, now i want to validate the data inside it. how can i achieve this other than the try catch? i want the validation to be usable in all my forms so i'll write it as a sub/function. any suggestions?

What specifically are you attempting to validate? Do you expect numbers, dates, strings, or a combination of all?

If you're expecting numbers, use Int32.TryParse for integer values or Single/Double/Decimal.TryParse for decimal values. For dates, use DateTime.TryParse.

TryParse(s as String, ByRef result as [Type]) is a function that accepts a string input as well as a reference to a variable of the type you are trying to use. If the input can be parsed, the function itself returns true and your parsed value is stored in the variable you passed in by reference. If the input cannot be parsed, the function simply returns false and the reference variable is returned as the default value of the type used. Obviously, in most instances you would be concerned about the "false" output and would disregard the variable.

An example usage:

Sub Main()

        Dim i As Integer = 17
        Console.WriteLine("Original value -- {0}", i)

        If (Int32.TryParse("abc", i)) Then
            Console.WriteLine("Successfully parsed the input as {0}", i)
        Else
            Console.WriteLine("Illegal input, variable set to default value -- {0}", i)
        End If

        Console.Read()

    End Sub

This is programmatically more efficient than simply relying on exception handling when using functions like Int32.Parse() or Convert.ToInt32(), and the true/false conditional path still allows you to handle invalid inputs.

This question has already been answered. Start a new discussion instead.