2012-09-05 60 views
2

處理什麼,我有以下功能:如何在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。爲什麼,以及如何解決它?

+0

幾乎是http://stackoverflow.com/q/11547008/256431的副本 –

回答

2

我會更改GetElementsByTagName,使它在For Each語句之外,這樣可以更容易地檢查Collection是否爲空或空。

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