Sam Valenzuela Sam Valenzuela - 1 year ago 155 Question

An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll

This is in Microsoft Visual Studio 2015. I'm using Visual Basic code, and I'm trying to make it so when a person inputs a name in txtPokemonInput, that it verifies that it is an actual name. When I run the code and type "Abra" into the textbox then click cmdCalculate, I get this error:

An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "Bellsprout" to type 'Boolean'

is not valid.

Here is the code:

Option Compare Text
Public Class Form1
Private Sub cmdCalculate_Click(sender As Object, e As EventArgs) Handles
If txtPokemonInput.Text <> "Abra" Or "Bellsprout" Then
MsgBox("Please input an actual Pokemon name.")
End If
End Sub
End Class

Answer Source


If txtPokemonInput.Text <> "Abra" Or "Bellsprout" Then

does not do what you intend. What it actually does is try to perform a logical OR operation on "Abra" and "Bellsprout" and then compare the Boolean result to that Text property. Performing Boolean logic with Strings is what leads to that invalid cast. The code to do what you actually want to do is this:

If txtPokemonInput.Text <> "Abra" AndAlso txtPokemonInput.Text <> "Bellsprout" Then

Note that it's a logical AND rather than a logical OR and the short-circuiting AndAlso operator is used in preference to the And operator.

I would strongly suggest that you turn Option Strict On in your project properties and also in the IDE options, so that all future projects will have it On by default. That will not stop you making mistakes like this but it will flag them as compilation errors rather then letting them through to be caught at run time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download