How to remove the 'Table of content'(No table of contents entries found) in word document if there is no content with Heading 1 to 3?

We have a template document in which we have defined the TOC: ‘{TOC \o “1-3” \h \z \u}’.

After creating a document with the template file, if the content in the document does not contain ‘Heading 1- 3’ then the word adds the below comment in the Table of Content area: 'No table of contents entries found’

Now, we don’t want to show the above message in the document in case there is no Heading1-3.

For this now we have written the following code:

if (!HeaderExist(templateDocument))
{
    RemoveTableOfContents(templateDocument);
    templateDocument.UpdateFields();
}
private static bool HeaderExist(Document document)
{
	NodeCollection paragraphs = document.GetChildNodes(NodeType.Paragraph, true);

	foreach (Paragraph paragraph in paragraphs)
	{
		switch (paragraph.ParagraphFormat.StyleIdentifier)
		{
			case StyleIdentifier.Heading1:
			case StyleIdentifier.Heading2:
			case StyleIdentifier.Heading3:
				return true;
		}
	}

	return false;
}

private static void RemoveTableOfContents(Document document)
{
	foreach (Field field in document.Range.Fields)
	{
		if (field.Type == FieldType.FieldTOC)
		{
			field.Remove();
		}
	}
}

Is there any direct or easy way to check and remove the above message in the document?
image.png (11.3 KB)

Please help us to fix this issue.

Thanks & Regards,
MS

@msindia Unfortunately, there is no built in way to remove TOC field without entries. Except your approach, you can also try using the approach where you check the display value of the updated TOC. For example see the following code:

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert TOC
builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
// insert some content.
builder.Writeln();
builder.Write("This is the document's content.");

// Update fields.
doc.UpdateFields();

// Check whether TOC has entries.
foreach (Field f in doc.Range.Fields)
{
    if ((f.Type == FieldType.FieldTOC) && f.DisplayResult == "No table of contents entries found.")
        f.Remove();
}

doc.Save(@"C:\Temp\out.docx");
1 Like

@alexey.noskov,

Thanks for your quick reply!..

1 Like