NietzscheProgrammer NietzscheProgrammer - 4 months ago 11
Vb.net Question

How to check if input comes null/empty

I need to check if an input comes null/empty.

If input <= 100 And input > 0 And Not input = "" Then

subjectsInt.Add(subjects(i), input)
check = True

End If


I know in that code I am checking it as String but I already did
Not input = Nothing
and
Not input = 0
and I am getting an error:


Run-time exception (line -1): Conversion from string "" to type 'Integer' is not valid.

Stack Trace:

[System.FormatException: Input string was not in a correct format.]

[System.InvalidCastException: Conversion from string "" to type 'Integer' is not valid.]


Any suggestions?

EDIT

Here is the code in case you want to take a look: https://dotnetfiddle.net/0QvoAo

Answer

Well, I have looked at your code and there are many problems, all caused by the freely approach to Data Types that VB.NET allows when you have Option Strict set to Off. In this context VB.NET allows you to assign the return value of Console.ReadLine to an Integer trying to help you adding an implicit conversion of the input. Of course if the user types ABCD this implicit conversion has no other way to inform you than triggering an Exception. So I really, really recommend you to use Option Strict set to On (MSDN Option Strict)

Now with Option Strict On your code has a lot of errors, I have rewritten your code and then explain in comments the changes.

Option Strict On
Imports System
Imports System.Collections.Generic

Public Module Module1
    Public Sub Main()
       Console.WriteLine("Hello World")

       ' I use a List of strings instead of an untyped array list
       Dim subjects As New List(Of String)() From  
       {
           "Math",
           "English", 
           "German"
       } 
       Dim subjectsInt As New System.Collections.Generic.Dictionary(Of String, Integer) 
       Dim i, input As Integer
       Dim check As Boolean

       For i = 0 To subjects.Count - 1
           check = False
           Do
               Console.WriteLine(subjects(i) & ": ")

               ' The input is passed to a string 
               Dim temp  = Console.ReadLine()

               ' Check if this string is really a number
               If Int32.TryParse(temp, input) Then
                  If input <= 100 And input > 0 Then
                       subjectsInt.Add(subjects(i), input)
                       check = True
                  End If
               End If
           Loop While check = False
       Next
       For i = 0 To subjects.Count - 1
          Console.WriteLine(subjects(i) & ": " & subjectsInt(subjects(i)))
       Next
       Console.ReadLine()
    End Sub
End Module
Comments