hello, I had to add an extra line to check whether the tag variable is null or not before the Console.WriteLine() otherwise I would be getting a null reference exception. thanks
If the contentcontrol sits inside a SdtCell, the above method might not be able to find it.
I added the SdtCell into this:
public static IEnumerable<OpenXmlElement> ContentControls(
this OpenXmlPart part)
{
return part.RootElement
.Descendants()
.Where(e => e is SdtBlock || e is SdtRun || e is SdtCell);
}
Thanks a lot for your post. I tried to run this sample code, but i am getting the following error and not able to proceed.
"'DocumentFormat.OpenXml.Packaging.OpenXmlPart.RootElement' is inaccessible due to its protection level". I just copied the code and try to run. I have added the reference to the corresponding DLL. Please guide me.
This is exactly what I need, however, I will need to go further and take values from a web form and edit the content control tags with the corresponding values. Thanks!
Hi Eric, you code works well for the attached docx file, but it doesn't Iterating through all Content Controls if one Content Control contains other Content Control.
I mean lets say, i have Rich Text Content Control with table inside & inside this table i have lets say CheckBox Content Control column for all the rows. These checkBox Content Control are not Iterate through.
It doesn't read the nested Content Controls.
Please help in this.
Thanks
Gill
Hi I am able to find the solution as
public static IEnumerable<OpenXmlElement> ContentControls(this OpenXmlPart part)
return part.RootElement.Descendants().Where(e => e is SdtBlock || e is SdtRun || e is SdtCell);
In case Some One need the same functionality in VB.Net (as we don't have yield return in VB.NET)
<System.Runtime.CompilerServices.Extension()> _
Public Function getDocumentContentControls(doc As WordprocessingDocument)
Dim lstElements As New List(Of OpenXmlElement)
For Each ContentControl As OpenXmlElement In GetPartContentControls(doc.MainDocumentPart)
lstElements.Add(ContentControl)
Next
For Each header As OpenXmlPart In doc.MainDocumentPart.HeaderParts
For Each ContentControl As OpenXmlElement In GetPartContentControls(header)
For Each footer As OpenXmlPart In doc.MainDocumentPart.FooterParts
For Each ContentControl As OpenXmlElement In GetPartContentControls(footer)
If doc.MainDocumentPart.FootnotesPart IsNot Nothing Then
Dim lobjFootNotes As OpenXmlPart = doc.MainDocumentPart.FootnotesPart
For Each ContentControl As OpenXmlElement In GetPartContentControls(lobjFootNotes)
End If
If doc.MainDocumentPart.EndnotesPart IsNot Nothing Then
Dim lobjEndNotes As OpenXmlPart = doc.MainDocumentPart.EndnotesPart
For Each ContentControl As OpenXmlElement In GetPartContentControls(lobjEndNotes)
Return lstElements
End Function
gsgill76 can you post the whole vb code for me please? You are referencing a method called GetPartContentControls and not too sure what that is doing in your code.