How do I fix Object reference not set to an instance of an object?
I get CompletedDate from XML document element name CompDate. This is an optional element. When the XML document has a CompDate element my VB.NET code works. However when the XML document does not have CompDate element, I get Object reference not set to an instance of an object?
How do I fix this so it works whether or not the CompDate element exist in the XML Document?
XML Document vb code is reading
Code:
<Integration>
<Case>
<CaseEvent ID="252949395">
<CompDate>06/01/2019</CompDate>
</CaseEvent>
</Case>
<IntegrationConditions>
<IntegrationCondition>
<NotificationEvent elementKey="252949395">InsertPWBRorAOS</NotificationEvent>
</IntegrationCondition>
</IntegrationConditions>
</Integration>
What I have tried:
VB.NET code
Code:
Dim strEventId As String
strEventId = aobjxmlNotificationEventNode.SelectSingleNode("@elementKey").InnerText
objInsertPWBRorAOS.CompletedDate = CDate(aobjXmlInputDoc.DocumentElement.SelectSingleNode("Case/CaseEvent[@ID=" + strEventId + "]/CompDate").InnerText)
Re: How do I fix Object reference not set to an instance of an object?
Thread moved from the 'CodeBank VB.Net' forum (which is for you to post working code examples, not questions) to the 'VB.Net' forum
I think this might solve it for you:
Code:
Dim strEventId As String
strEventId = aobjxmlNotificationEventNode.SelectSingleNode("@elementKey").InnerText
Dim CompDate = aobjXmlInputDoc.DocumentElement.SelectSingleNode("Case/CaseEvent[@ID=" + strEventId + "]/CompDate")
If CompDate IsNot Nothing Then
objInsertPWBRorAOS.CompletedDate = CDate(CompDate.InnerText)
End If
Re: How do I fix Object reference not set to an instance of an object?
VB also has null propagation these days, so you can say "get this member if the object exists, otherwise get Nothing":
vb.net Code:
Dim strEventId As String
strEventId = aobjxmlNotificationEventNode.SelectSingleNode("@elementKey").InnerText
Dim CompDate = aobjXmlInputDoc.DocumentElement.SelectSingleNode("Case/CaseEvent[@ID=" + strEventId + "]/CompDate")?.InnerText
If CompDate IsNot Nothing Then
objInsertPWBRorAOS.CompletedDate = CDate(CompDate)
End If
This:
is functionally equivalent to this:
vb.net Code:
If y Is Nothing Then
x = Nothing
Else
x = y.z
End If
One of the cool things is that, because you can use the null propagation operator anywhere you would use a standard member access operator, you can chain them together, e.g.
That is functionally equivalent to this:
vb.net Code:
If b Is Nothing OrElse b.c Is Nothing OrElse b.c.d Is Nothing Then
a = Nothing
Else
a = b.c.d.e
End If
Note that null propagation only works for reference types or nullable value types.