Introduction
Content controls provide a user interface (UI), which has controlled input like a form, preventing users from editing or deleting protected areas of a document. This is useful, if you have information in a document or a template that users should be able to read but not edit, or if you want the users to be able to edit the content controls but not delete them.
There are basically ten types of content controls in Word 2013. This article mainly introduces how we can add most commonly used content controls, including Rich Text, Plain Text, Picture, Combo Box, Drop-Down List and Date Picker to Word document at the run time.
Background
I used a .NET Word component to simplify my task, which can be easily downloaded and installed into Visual Studio via NuGet. After installation, we should also add following necessary namespaces at the beginning.
- using Spire.Doc;
- using Spire.Doc.Documents;
- using Spire.Doc.Fields;
- using System;
- using System.Drawing;
Using the code
The following parts will demonstrate how to add a Drop-Down List content control to a Word document. The code snippets of creating other controls is quite similar to this one and can be found at the end of this article.
STEP 1
Create a new Word document, add a section to the document and a paragraph to the section.
- Document document = new Document();
- Section section = document.AddSection();
- Paragraph paragraph = section.AddParagraph();
STEP 2
Initialize an instance of StructureDocumentTagInline class, which represents a content control in Word. Call Paragraph.ChildObjects.Add() method to add the content control to the paragraph and specify its SDT type to Drop-Down List.
- StructureDocumentTagInline sd = new StructureDocumentTagInline(document);
- paragraph.ChildObjects.Add(sd);
- sd.SDTProperties.SDTType = SdtType.DropDownList;
STEP 3
Set the title and tag of the content control.
- sdt.SDTProperties.Alias = "Drop-down list";
- sdt.SDTProperties.Tag = "Drop-down list";
STEP 4
Initialize an instance of SdtDropDownList class, add the items to the list and assign the values to Drop-Down List properties.
- SdtDropDownList sddl = new SdtDropDownList();
- sddl.ListItems.Add(new SdtListItem("Male","1"));
- sddl.ListItems.Add(new SdtListItem("Female","2"));
- sdt.SDTProperties.ControlProperties = sddl;
STEP 5
Set the display text of the control.
- TextRange rt = new TextRange(document);
- rt.Text = sddl.ListItems[0].DisplayText;
- sdt.SDTContent.ChildObjects.Add(rt);
STEP 6
Save the file with the specified file path.
- document.SaveToFile("Controls.docx", FileFormat.Docx);
Entire Code