How do I fix Object reference not set to an instance of an object? RRS feed

  • General discussion

  • 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

    		<CaseEvent ID="252949395">
    			<NotificationEvent elementKey="252949395">InsertPWBRorAOS</NotificationEvent>

    VB.NET code 

    Dim strEventId As String
    strEventId = aobjxmlNotificationEventNode.SelectSingleNode("@elementKey").InnerText
    objInsertPWBRorAOS.CompletedDate = CDate(aobjXmlInputDoc.DocumentElement.SelectSingleNode("Case/CaseEvent[@ID=" + strEventId + "]/CompDate").InnerText)

    Thursday, July 18, 2019 10:20 PM

All replies

  • Good Day, 

    You've likely figured this out by now but if not...

    I would recommend using if statements to check for the elements being null before trying to assign them to variables.

    Saturday, September 14, 2019 8:52 PM
  • Hello winkimjr2,

    Either you can put try...catch block or you can enable exception settings by going to Debug menu >>Windows >> Exception Settings

    Then you can check the checkbox "Common Language Runtime Excpetions".

    Once checked, you can launch your application in debug mode. Visual studio will automatically break the execution at the pain point. Hope this would help you.

    For your exact query:

    Before passing below parameter to CDate, you can store it in a variable and do null check.

    aobjXmlInputDoc.DocumentElement.SelectSingleNode("Case/CaseEvent[@ID=" + strEventId + "]/CompDate").InnerText


    Monday, September 16, 2019 7:09 AM