dynamic content control mapping for MS word c#

610 views Asked by At

I am using code like this:

public void BindControlsToCustomXmlPart()
    {

          wordApp = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");

          foreach (Word.ContentControl contentControl in wordApp.ActiveDocument.ContentControls)
          {
              if (contentControl.Tag == "FieldName")
              {
                  string xPathFieldName = "ns:records/ns:record/ns:FieldName";

                  contentControl.XMLMapping.SetMapping(xPathFieldName,
                    prefix, currentWordDocumentXMLPart);
              }

What ends up happening is every new field I want to add, I have to repeat this redundant code:

              if (contentControl.Tag == "FieldName2")
              {
                  string xPathFieldName2 = "ns:records/ns:record/ns:FieldName2";

                  contentControl.XMLMapping.SetMapping(xPathFieldName2,
                    prefix, currentWordDocumentXMLPart);
              }

Is there a way that I can write this code once and have the "FieldName" portion get updated for each field dynamically? i.e. have some type of loop that would increment through each xmlnode in an xml file (in this case it would map the xml node FieldName to the content control with a tag of FieldName, and then map the xml node FieldName2 to the content control with a tag of FieldName2

1

There are 1 answers

0
legrandviking On

A good start would be creating a function to transform your control and reuse that function multiple times as followed

public contentControl BindControlsOperation(contentControl control, string pFieldName)
{
          if (control.Tag == pFieldName)
          {
             string xPathFieldName = String.Format("ns:records/ns:record/ns:{0}",pFieldName);
             control.XMLMapping.SetMapping(xPathFieldName,prefix, currentWordDocumentXMLPart);
          }

          return control;
 }

You could then use it in the following fashion

  foreach (Word.ContentControl contentControl in wordApp.ActiveDocument.ContentControls)
  {
          contentControl = BindControlsOperation(contentControl,"FieldName")
  }

Next step would be to have a list of names you want to use for fields and feed it to your algorythm using a for loop

.... 
List<string> names = "x,y,z";

for(int i=0;i < names.length();i++)
{
 wordApp.ActiveDocument.ContentControls[i] = BindControlsOperation(wordApp.ActiveDocument.ContentControls[i],name[i])
}

Hope this helps