How to unlock a content control using the OpenXML SDK in a Word 2010 document?

I am manipulating a Word 2010 document on the server side, and some document content controls have the following locking properties:

  • Content control cannot be removed
  • Content cannot be edited.

Can anyone advise setting these lock options to false or delete and then use the OpenKML SDK?

+6
source share
2 answers

The openxml SDK provides the Lock class and the LockingValues enumeration for programmatically setting parameters:

  • Content control cannot be deleted and
  • Content cannot be edited.

So, to set these two parameters to false ( LockingValues.Unlocked ), find all the SdtElement elements in the document and set the Val property to LockingValues.Unlocked .

The code below shows an example:

 static void UnlockAllSdtContentElements() { using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(@"c:\temp\myword.docx", true)) { IEnumerable<SdtElement> elements = wordDoc.MainDocumentPart.Document.Descendants<SdtElement>(); foreach (SdtElement elem in elements) { if (elem.SdtProperties != null) { Lock l = elem.SdtProperties.ChildElements.First<Lock>(); if (l == null) { continue; } if (l.Val == LockingValues.SdtContentLocked) { Console.Out.WriteLine("Unlock content element..."); l.Val = LockingValues.Unlocked; } } } } } static void Main(string[] args) { UnlockAllSdtContentElements(); } 
+5
source

Only for those who copy this code, keep in mind that if there are no locks associated with the content control, then there will be no Lock property associated with it, therefore, when the code executes the following statement, it will throw an exception, since the element does not found:

 Lock l = elem.SdtProperties.ChildElements.First<Lock>(); 

To fix this, do FirstOrDefault instead of First .

+1
source

All Articles