How do I unlock a content control using the OpenXML SDK in a Word 2010 document?
Asked Answered
E

2

6

I am manipulating a Word 2010 document on the server-side and some of the content controls in the document have the following Locking properties checked

  • Content control cannot be deleted
  • Contents cannot be edited

Can anyone advise set these Locking options to false or remove then altogether using the OpenXML SDK?

Electrocardiograph answered 23/5, 2012 at 21:55 Comment(0)
M
5

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

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

So, to set those two options to "false" (LockingValues.Unlocked), search for all 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();
}
Maharajah answered 4/6, 2012 at 19:31 Comment(0)
B
1

Just for the ones who copy this code, keep in mind that if there is no Locks associated to the content control, then there won't be a Lock property associated to it, so when the code executes the following instruction, it will return a exception since there is no element found:

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

The way to fix this is do the FirstOrDefault instead of First.

Berniecebernier answered 30/6, 2016 at 10:26 Comment(2)
Should be added as a comment to relevant solutionCraftsman
Hi @OriPrice, i cannot comment the solution since my reputation is below 50. Regards.Berniecebernier

© 2022 - 2024 — McMap. All rights reserved.