0

Why do I get Conversion from string "" to type 'Integer' is not valid.? Match is a string, and when I compare it to "" it gives me this error. The program works when values are entered etc. but if I want to check for an empty string (the last ElseIf) I get an error.

Dim total As Double
Dim Match As String = ""

If Match.EndsWith("HA") OrElse Match.Contains("ha") OrElse Match.Contains("Ha") Then
    Dim nonNumericCharacters As New Regex("\D")
    Dim numericOnlyString As String = nonNumericCharacters.Replace(Match, String.Empty)
    total = numericOnlyString * 10000
ElseIf Match.Contains("Ha m²") Then
    Dim nonNumericCharacters As New Regex("\D")
    Dim numericOnlyString As String = nonNumericCharacters.Replace(Match, String.Empty)
    total = numericOnlyString * 10000
ElseIf Match.Contains("m²") OrElse Match.Contains("sqm") Then
    Dim nonNumericCharacters As New Regex("\D")
    Dim numericOnlyString As String = nonNumericCharacters.Replace(Match, String.Empty)
    total = Val(numericOnlyString)
ElseIf CInt(Match) = 0 OrElse Match = "" Then
    total = Val(String.Empty)
Else
    total = Match
End If
MessageBox.Show(total)
1
  • 2
    Because an empty string "" is not a number. You should reorder the expression to: ((Match = "") OrElse (CInt(Match) = 0)) Commented Jul 31, 2014 at 11:08

2 Answers 2

1

As commented by Bjørn-Roger Kringsjå, you need to re-order the expression to check for 'bad' strings first. Also, you can't set the total to the Val of an empty string. Your code could be adjusted to;

...
ElseIf Match = "" OrElse CInt(Match) = 0 Then
    total = 0
Else
...

However, in order to let you learn a few things, I would re-write that section of code like this;

Dim ParseResult As Integer    
...
ElseIf String.IsNullOrWhiteSpace(Match) OrElse Not Integer.TryParse(Match, ParseResult) Then
    total = 0
Else
...

This first checks if the Match string is Nothing, empty or just spaces/tabs/etc, then if not, tries to parse it to an Integer. If that fails, then the total is set to zero. You should of course do it all with Integer.TryParse and use the result, but I hope that helps.

Sign up to request clarification or add additional context in comments.

Comments

0

You get "Conversion from string "" to type 'Integer' is not valid." because the conversion from string "" to type 'Integer' is not valid.

"" is not a valid number.

You need to detect this case and pick the right number yourself, like 0, but attempting the conversion will give you that exception.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.