Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 440
  • Last Modified:

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?
0
jdklem
Asked:
jdklem
  • 3
  • 2
1 Solution
 
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
 
CodeCruiserCommented:
It looks like the

GetFirstChild(Of Tag)

is returning nothing.
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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now