.NET
Microsoft Technologies based on the .NET software framework.
4,103 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Is there A role to change anykind of content control in a word.docm without breaking the file itself ?
In this example I am trying to change the value of SdtContentDate. After changing and save the file I get the following error.
I'm using this code to get the element by tag
public IEnumerable<OpenXmlElement> ContentControls( OpenXmlPart part)
{
if (part.RootElement != null)
{
return part.RootElement.Descendants().Where(e => e is SdtElement);
}
return new List<OpenXmlElement>();
}
public IEnumerable<OpenXmlElement> ContentControls( WordprocessingDocument doc)
{
if (doc.MainDocumentPart != null)
{
foreach (var cc in ContentControls(doc.MainDocumentPart))
{
yield return cc;
}
foreach (var header in doc.MainDocumentPart.HeaderParts)
{
foreach (var cc in ContentControls(header))
{
yield return cc;
}
}
foreach (var footer in doc.MainDocumentPart.FooterParts)
{
foreach (var cc in ContentControls(footer))
{
yield return cc;
}
}
if (doc.MainDocumentPart.FootnotesPart != null)
{
foreach (var cc in ContentControls(doc.MainDocumentPart.FootnotesPart))
{
yield return cc;
}
}
if (doc.MainDocumentPart.EndnotesPart != null)
{
foreach (var cc in ContentControls(doc.MainDocumentPart.EndnotesPart))
{
yield return cc;
}
}
}
}
public List<OpenXmlElement> FindContentControlByTag( WordprocessingDocument doc, string tag)
{
IEnumerable<OpenXmlElement>? ccs = ContentControls(doc);
List<OpenXmlElement>? output = new();
if (ccs != null)
{
foreach (var cc in ccs)
{
SdtProperties? props = cc.Elements<SdtProperties>().FirstOrDefault();
if (props != null)
{
DocumentFormat.OpenXml.Wordprocessing.Tag? tagElement = props.Elements<DocumentFormat.OpenXml.Wordprocessing.Tag>().FirstOrDefault();
if (tagElement != null)
{
//Console.WriteLine(tagElement.Val);
if (tagElement.Val == tag)
{
output.Add(cc);
}
}
}
}
}
return output;
}
My problem after I select the sdtContentControl I can't change it's value
List<OpenXmlElement> elements = FindContentControlByTag(document, "sdate");
OpenXmlElement cc = elements.First();
var datePickers = cc.Descendants<SdtContentDate>().ToList();
SdtContentDate datePicker = datePickers.First();
datePicker.FullDate = new DateTimeValue(DateTime.Now);
After saving the document I get this error