ProgrammingDesktop application developer in Visual Basic

How to implement user input processing (e.g., from a TextBox) while ensuring that the input is a number and preventing type conversion errors in Visual Basic?

Pass interviews with Hintsage AI assistant

Answer.

In processing user input, it is critically important to prevent type conversion errors when a user, for example, enters something other than a number in a TextBox. This is crucial for ensuring application robustness.

Background:

In VB6 and VB.NET, conversion errors (for example, using CInt or Val) led to crashes. Later, safer means such as Integer.TryParse were introduced.

Problem:

When attempting to convert invalid data (letters, special characters, an empty string), standard methods (CInt, CDbl) throw exceptions. As a result, the application may crash.

Solution:

For safe conversion, use TryParse. It returns a Boolean indicating the success of the string-to-number conversion and prevents exceptions.

Example code:

Dim input As String = TextBox1.Text Dim number As Integer If Integer.TryParse(input, number) Then MessageBox.Show($"You entered the number: {number}") Else MessageBox.Show("Error: input is not a number") End If

Key features:

  • TryParse does not throw exceptions on failure
  • Allows flexible response to invalid input
  • Fully compatible with localization and formats

Trick questions.

What does the function Val("123abc") return and why can this be dangerous?

Val("123abc") will return 123, ignoring non-numeric characters after the number, leading to errors if the user accidentally inputs an extra character.

Can an empty string be converted with CInt("")?

No, the function will throw an InvalidCastException.

What approach should be taken for floating-point numbers considering localization?

Use Double.TryParse with specifying CultureInfo, as in some locales a comma , is the decimal separator, while in others it is a dot ..

Dim value As Double Dim isParsed = Double.TryParse("3,14", NumberStyles.Any, CultureInfo.CurrentCulture, value)

Common mistakes and anti-patterns

  • Using Val for obtaining a number with uncontrolled results
  • Applying CInt without checking the content
  • Lack of user error messages for input mistakes

Real-life example

Negative case

A developer directly converts the text from the field to a number: Dim n = CInt(TextBox1.Text) without checking.

Pros:

  • Minimal code

Cons:

  • The program crashes on invalid input
  • No error messages

Positive case

TryParse is used with user notification of incorrect input (see the example above).

Pros:

  • Robust application
  • Improved user experience

Cons:

  • More code is needed for error handling and localization of messages