我对visual basic相当新,所以它可能很明显,但我认为没有理由抛出异常错误。 这是问题代码:
Public Sub textBoxFilePath_TextChanged(sender As Object, e As EventArgs) Handles textboxFilePath.TextChanged If textboxFilePath.Text.Trim.Length > 0 Then If My.Computer.FileSystem.FileExists(textboxFilePath.Text) Then Dim checkType As String checkType = System.IO.Path.GetExtension(textboxFilePath.Text) If checkType = ".xlsx" Or ".xls" Or ".xlsm" Then requiredPath = True Else requiredPath = False End If End If End If我得到的错误是
Microsoft.VisualBasic.dll中发生未处理的“System.InvalidCastException”类型异常
附加信息:从字符串“.xls”到“布尔”类型的转换无效。
有任何想法吗?
I am fairly new to visual basic, so it may be obvious, but I see no reason for this to throw and uncasted exception error. Here is the problem code:
Public Sub textBoxFilePath_TextChanged(sender As Object, e As EventArgs) Handles textboxFilePath.TextChanged If textboxFilePath.Text.Trim.Length > 0 Then If My.Computer.FileSystem.FileExists(textboxFilePath.Text) Then Dim checkType As String checkType = System.IO.Path.GetExtension(textboxFilePath.Text) If checkType = ".xlsx" Or ".xls" Or ".xlsm" Then requiredPath = True Else requiredPath = False End If End If End IfThe error I am getting is
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string ".xls" to type 'Boolean' is not valid.
Any ideas?
最满意答案
尝试这个:
If checkType = ".xlsx" Or checkType = ".xls" Or checkType = ".xlsm" Then requiredPath = True Else requiredPath = False End If您的代码试图评估“.xls”(这是一个字符串),它不能很好地转换为布尔值true / false。
你也可以这样做来应用“短路”,所以只评估第一个是真的:
If checkType = ".xlsx" OrElse checkType = ".xls" OrElse checkType = ".xlsm" Then requiredPath = True Else requiredPath = False End IfTry this:
If checkType = ".xlsx" Or checkType = ".xls" Or checkType = ".xlsm" Then requiredPath = True Else requiredPath = False End IfYour code was trying to evaluate ".xls" (which is a string), which does not convert nicely to a boolean true/false.
You could also do this to apply "short circuiting", so only the first one true is evaluated:
If checkType = ".xlsx" OrElse checkType = ".xls" OrElse checkType = ".xlsm" Then requiredPath = True Else requiredPath = False End If更多推荐
发布评论