How do I keep a MSWord TOC from crashing a VB .NET Descendants search?

I have used the following line of code to search for sdtBlocks in the Body XML of a Word 2007 document:

Dim vblMilestone As SdtBlock = vptMainPart.Document.Body.Descendants(Of SdtBlock)().Where(Function(r) r.SdtProperties.GetFirstChild(Of Tag).Val = "milDetails").Single

This code works great as long as there is not a Table of Contents in the document before the sdtBlock I am searching for.  If it finds a TOC first, it gives an Object error.

Obviously I can always add my TOC last, but I would like to already have it in the Template Document I am using.  Can anyone help?
jdklemAsked:
Who is Participating?
 
CodeCruiserConnect With a Mentor Commented:
It looks like the

GetFirstChild(Of Tag)

is returning nothing.
0
 
CodeCruiserCommented:
>If it finds a TOC first, it gives an Object error.
What is the exact error? Is it due to the ".Single" call?
0
 
jdklemAuthor Commented:
The error message says, "Object reference not set to an instance of an object".

I also tried using ".FirstOrDefault".

Is there anything else I can try?
0
 
jdklemAuthor Commented:
I put the TOC in a Content Control with a tag name.
I verified in the document.xml that the Tag child with a Val was there, but it still crashed with the same error.
0
 
jdklemAuthor Commented:
Your GetFirstChild(Of Tag) led me to look more closely into the TOC XML.  I found the TOC is a sdtBlock without a Tag.  I manually added the Tag property to the sdtBlock, and now it works.

Putting the TOC in a Content Control didn't work because that just put the sdtBlock inside an sdtBlock and buried the problem deeper.
0
All Courses

From novice to tech pro — start learning today.