2

私は次の機能を持っています:

 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 をスローすることがあります。なぜ、どうすれば修正できますか?

4

1 に答える 1

2

GetElementsByTagNameコレクションが Null であるか空であるかを簡単に確認できるように、For Each ステートメントの外にあるように変更します。

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
于 2012-09-05T01:34:16.220 に答える