• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 453
  • 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

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