NietzscheProgrammer NietzscheProgrammer - 1 year ago 68 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
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?


Here is the code in case you want to take a look:

Answer Source

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  
       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
               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
       For i = 0 To subjects.Count - 1
          Console.WriteLine(subjects(i) & ": " & subjectsInt(subjects(i)))
    End Sub
End Module
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download