How to prevent non-numeric input in VB.NET?

I am working on a program that requires the user to enter an integer. How to prevent a user from entering a non-numeric value? I tried using the IsNumeric () function, but I get an error message before I can use it. I get an error on console.read before I can call the IsNumeric () function. Here is my code:

Dim num As Integer Console.Write("enter num:") num = Console.ReadLine If IsNumeric(num) = True Then Console.WriteLine("valid. num = " & num) Else Console.WriteLine("invalid") End If 

Any help is appreciated.

+4
source share
5 answers

Try the following:

 Dim num As Integer Console.Write("enter num:") Dim input = Console.ReadLine If Integer.TryParse(input, num) Then Console.WriteLine("valid. num = " & num) Else Console.WriteLine("invalid") End If 
+7
source

This is exactly the situation for which Integer.TryParse() is intended. TryParse will return false if the string you are testing cannot be converted to an integer.

+5
source

Rather try something like:

 Dim num as Integer Console.Write("Enter num: ") While (Not (Integer.TryParse(num, Console.ReadLine()))) Console.WriteLine("Please enter an Integer only: ") End While 

The TryParse method tries to parse the input value and returns false when the value cannot be parsed by the specified type. The above code will ask for the values ​​used to enter until they enter an integer.

+1
source

You can read a string and then try to convert it to an integer. Trap any exceptions thrown by conversion to handle non-numeric input.

0
source

In C # sorry ...

 using System; class Program { static void Main(string[] args) { int a = GetNumericInput(); Console.WriteLine("Success, number {0} entered!",a); Console.Read(); } private static int GetNumericInput() { int number; string input; bool first = true; do { if (!first) { Console.WriteLine("Invalid Number, try again"); } Console.WriteLine("enter a number"); input = Console.ReadLine(); first = false; } while (!int.TryParse(input, out number)); return number; } } 
0
source