VB.Net Exception已被调用的目标抛出



我在VB中使用以下代码。Net (Winforms)可以简单地遍历DataGridView并隐藏不需要的行。

Private Sub Overview_Workstream_Sort_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Overview_Workstream_Sort.SelectedIndexChanged
    For Each row In Incident_Persons_List.Rows
        If Incident_Persons_List.Rows(CInt(row)).Cells(7).Value.ToString.Contains(Overview_Workstream_Sort.SelectedItem.ToString) Then
            Debug.Print("User found in workstream")
            Incident_Persons_List.Rows(CInt(row)).Visible = True
        Else
            Incident_Persons_List.Rows(CInt(row)).Visible = False
        End If
    Next
End Sub

当调试器到达IF语句的第一行时,我得到以下错误:

类型的未处理异常"System.Reflection。TargetInvocationException'在mscorlib.dll中发生

附加信息:异常已被对象抛出调用。

我一直在尝试我能想到的一切来理解为什么会这样。我已经查了这个错误,但是当抛出这个异常时,每个人似乎都有完全不同的问题。

是否与我进行比较的方式有关?

更新1

  1. 我已经删除了For Each并将其替换为For i = 0 to Incident_Persons_list.Rows.Count
  2. 我删除了Cint指令
  3. Try/Catch显示实际抛出的异常是:

无法生成与货币管理器位置关联的行看不见。

更新2

现在一切都正常工作,下面的代码:

 Private Sub Overview_Workstream_Sort_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Overview_Workstream_Sort.SelectedIndexChanged
        Try
            For i = 0 To Incident_Persons_List.Rows.Count - 1
                If Incident_Persons_List.Rows(i).Cells(7).Value.ToString.Contains(Overview_Workstream_Sort.SelectedItem.ToString) Then
                    Debug.Print("User found in workstream")
                    Incident_Persons_List.Rows(i).Visible = True
                Else

                    'Your code that will throw the Exception
                    Incident_Persons_List.CurrentCell = Nothing
                    Incident_Persons_List.Rows(i).Visible = False
            End If
        Next
        Catch ex As TargetInvocationException
            'We only catch this one, so you can catch other exception later on
            'We get the inner exception because ex is not helpfull
            Dim iEX = ex.InnerException
            Debug.Print(iEX.Message)
        Catch ex As Exception
            Debug.Print(ex.Message)
        End Try
    End Sub

谢谢你的帮助!

TargetInvocationException:

通过反射调用的方法引发的异常

如何发现发生了什么(因为那个异常并没有真正的帮助)?

必须用Try/Catch结构包围调用块,然后检查捕获的InnerException:

Try
    'Your code that will throw the Exception
Catch ex As TargetInvocationException
    'We only catch this one, so you can catch other exception later on
    'We get the inner exception because ex is not helpfull
    Dim iEX = ex.InnerException
    'Now you can do some stuff to handle your exception
Catch ex As Exception
    'Here you catch other kinds of Exceptions that could occur in your code, if you want to...
End Try

因为您的行变量是Incident_Persons_List的枚举元素。行,而不是集合中我认为应该替换的元素的索引。

Incident_Persons_List.Rows(CInt(row))

row

或者使用基本的for结构代替foreach。Somethink像

For row = 0 To Incident_Persons_List.Rows.Count - 1 Step 1
   //SomeStuff
Next

最新更新