How to handle nothing in a foreach loop
Domanda
I have the following function:
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
Sometimes the commented line throws a NullReferenceException. Why, and how do I fix it?
Soluzione
I would change the GetElementsByTagName
so that it is outside of the For Each statement that way it will be easier to check if the Collection is Null or 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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow