title: Creating MS Word Content Controls on a loop
body: <p>I'm an experienced C# developer who drew the short straw on this particular phase of the project and got to work on document generation (no-one on the team has any particular experience with this).</p>
  
  <p>For Word output, so far, I've been using Content Controls embedded in documents and some of the methods in the DocumentFormat.OpenXml package to create fields I can identify in code and dynamically replace with the appropriate data. So I load a template, and loop through the content controls like this:</p>
  
  <pre><code>string template = serverRoot + @"Templates\MyTemplate.docx";
  string path = serverRoot + @"DataOut\\" + clientName + "\\MyDocument.docx";
  File.Copy(template, path, true);
  
  using (WordprocessingDocument newDoc = WordprocessingDocument.Open(path, true))
  {
      MainDocumentPart mainPart = newDoc.MainDocumentPart;
      var placeHolders = mainPart.Document.Body.Descendants&lt;SdtElement&gt;();
  
      foreach (var sdtRun in placeHolders)
      {
          Console.WriteLine("Found Field: " + sdtRun.SdtProperties.GetFirstChild&lt;Tag&gt;().Val.Value);
          switch (sdtRun.SdtProperties.GetFirstChild&lt;Tag&gt;().Val.Value)
          {
              //check the content control values and replace them
          }
      }
  }
  </code></pre>
  
  <p>However, my next document requires an indeterminate number of repeat elements depending on the situation. Or to put it another way, for each file in the package it need to output something like this into the doc:</p>
  
  <pre><code>Filename: &lt;insert filename&gt;
  Quantity: &lt;insert quantity&gt;
  Date:     &lt;insert date&gt;
  </code></pre>
  
  <p>But we don't know in advance how many files there will be.</p>
  
  <p>AFAIK I can't do this with a standard content control, at least not while retaining any kind of sensible formatting. </p>
  
  <p>What's the best approach here. Should I generate the whole text as a block, adding in line breaks and such, and stuff it all into one Content Control? Create new Content Controls on the fly (and if so, how)? Or is there a better way?</p>