About to go mad with this problem. I'm sure it's so simple I'm just missing it, but I cannot for the life of me find out how to change the content of a content control in Word 2007 with the OpenXml SDK v2.0 in C#.
I have created a Word document with a plain text content control. The tag for this control is "FirstName". In code, I'd like to open up the Word document, find this content control, and change the content without losing the formatting.
The solution I finally got to work involved finding the content control, inserting a run after it, then removing the content control as such:
using (WordprocessingDocument wordProcessingDocument = WordprocessingDocument.Open(filePath, true)) {
MainDocumentPart mainDocumentPart = wordProcessingDocument.MainDocumentPart;
SdtRun sdtRun = mainDocumentPart.Document.Descendants<SdtRun>()
.Where(run => run.SdtProperties.GetFirstChild<Tag>().Val == "FirstName").Single();
if (sdtRun != null) {
sdtRun.Parent.InsertAfter(new Run(new Text("John")), sdtRun);
sdtRun.Remove();
}
This does change the text, but I lose all formatting. Does anyone know how I can do this?