Как ничего не обрабатывать в цикле foreach

У меня есть следующая функция:

 Public Sub performautowebrowserOperations()
    Try
        For Each link As HtmlElement In WebBrowser2.Document.GetElementsByTagName("input") 'sometimes throws a null reference exception
            If link.GetAttribute("value") IsNot Nothing Then
                If link.GetAttribute("value") = "Compare prices" Then
                    link.InvokeMember("click")
                End If
            End If
        Next
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

Иногда закомментированная строка вызывает исключение NullReferenceException. Почему и как это исправить?


person user1570048    schedule 05.09.2012    source источник
comment
почти дубликат stackoverflow.com/q/11547008/256431   -  person Mark Hurd    schedule 05.09.2012


Ответы (1)


Я бы изменил GetElementsByTagName так, чтобы он находился за пределами оператора For Each, чтобы было легче проверить, является ли коллекция Null или Empty.

Public Sub performautowebrowserOperations()
    Try
        Dim elements As HtmlElementCollection = WebBrowser2.Document.GetElementsByTagName("input")
        If Not IsNothing(elements) And elements.Count > 0 Then
            For Each link As HtmlElement In elements
                If link.GetAttribute("value") IsNot Nothing Then
                    If link.GetAttribute("value") = "Compare prices" Then
                        link.InvokeMember("click")
                    End If
                End If
            Next
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub
person Mark Hall    schedule 05.09.2012