News Category

Form Field

Form Field (7)

A cross-reference refers to related information elsewhere in the same document. You can create cross-references to any existing items such as headings, footnotes, bookmarks, captions, and numbered paragraphs. This article will show you how to create a cross-reference to bookmark using Spire.Doc with C# and VB.NET.

Step 1: Create a Document instance.

Document doc = new Document();
Section section = doc.AddSection();

Step 2: Insert a bookmark.

Paragraph paragraph = section.AddParagraph();
paragraph.AppendBookmarkStart("MyBookmark");
paragraph.AppendText("Text inside a bookmark");
paragraph.AppendBookmarkEnd("MyBookmark");

Step 3: Create a cross-reference field, and link it to the bookmark through bookmark name.

Field field = new Field(doc);
field.Type = FieldType.FieldRef;
field.Code = @"REF MyBookmark \p \h";

Step 4: Add a paragraph, and insert the field to the paragraph.

paragraph = section.AddParagraph();
paragraph.AppendText("For more information, see ");
paragraph.ChildObjects.Add(field);

Step 5: Insert a FieldSeparator object to the paragraph, which works as separator in a field.

FieldMark fieldSeparator= new FieldMark(doc, FieldMarkType.FieldSeparator);
paragraph.ChildObjects.Add(fieldSeparator);

Step 6: Set the display text of the cross-reference field.

TextRange tr = new TextRange(doc);
tr.Text = "above";
paragraph.ChildObjects.Add(tr);

Step 7: Insert a FieldEnd object to the paragraph, which is used to mark the end of a field.

FieldMark fieldEnd = new FieldMark(doc, FieldMarkType.FieldEnd);
paragraph.ChildObjects.Add(fieldEnd);

Step 8: Save to file.

doc.SaveToFile("output.docx", FileFormat.Docx2013);

Output:

The cross-reference appears as a link that takes the reader to the referenced item.

Create a Cross-Reference to Bookmark in Word in C#, VB.NET

Full Code:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace CreatCR
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            Section section = doc.AddSection();
            //create a bookmark
            Paragraph paragraph = section.AddParagraph();
            paragraph.AppendBookmarkStart("MyBookmark");
            paragraph.AppendText("Text inside a bookmark");
            paragraph.AppendBookmarkEnd("MyBookmark");
            //insert line breaks
            for (int i = 0; i < 4; i++)
            {
                paragraph.AppendBreak(BreakType.LineBreak);
            }
            //create a cross-reference field, and link it to bookmark                    
            Field field = new Field(doc);
            field.Type = FieldType.FieldRef;
            field.Code = @"REF MyBookmark \p \h";
            //insert field to paragraph
            paragraph = section.AddParagraph();
            paragraph.AppendText("For more information, see ");
            paragraph.ChildObjects.Add(field);
            //insert FieldSeparator object
            FieldMark fieldSeparator = new FieldMark(doc, FieldMarkType.FieldSeparator);
            paragraph.ChildObjects.Add(fieldSeparator);
            //set display text of the field
            TextRange tr = new TextRange(doc);
            tr.Text = "above";
            paragraph.ChildObjects.Add(tr);
            //insert FieldEnd object to mark the end of the field
            FieldMark fieldEnd = new FieldMark(doc, FieldMarkType.FieldEnd);
            paragraph.ChildObjects.Add(fieldEnd);
            //save file
            doc.SaveToFile("output.docx", FileFormat.Docx2013);

        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Namespace CreatCR
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New Document()
			Dim section As Section = doc.AddSection()
			'create a bookmark
			Dim paragraph As Paragraph = section.AddParagraph()
			paragraph.AppendBookmarkStart("MyBookmark")
			paragraph.AppendText("Text inside a bookmark")
			paragraph.AppendBookmarkEnd("MyBookmark")
			'insert line breaks
			For i As Integer = 0 To 3
				paragraph.AppendBreak(BreakType.LineBreak)
			Next
			'create a cross-reference field, and link it to bookmark                    
			Dim field As New Field(doc)
			field.Type = FieldType.FieldRef
			field.Code = "REF MyBookmark \p \h"
			'insert field to paragraph
			paragraph = section.AddParagraph()
			paragraph.AppendText("For more information, see ")
			paragraph.ChildObjects.Add(field)
			'insert FieldSeparator object
			Dim fieldSeparator As New FieldMark(doc, FieldMarkType.FieldSeparator)
			paragraph.ChildObjects.Add(fieldSeparator)
			'set display text of the field
			Dim tr As New TextRange(doc)
			tr.Text = "above"
			paragraph.ChildObjects.Add(tr)
			'insert FieldEnd object to mark the end of the field
			Dim fieldEnd As New FieldMark(doc, FieldMarkType.FieldEnd)
			paragraph.ChildObjects.Add(fieldEnd)
			'save file
			doc.SaveToFile("output.docx", FileFormat.Docx2013)

		End Sub
	End Class
End Namespace

We have already demonstrated how to add a brand new TOC when we create the word documents. This article will show you how to insert a TOC to the existing word documents with styles and remove the TOC from the word document.

Firstly, view the sample document with Title, Heading1 and Heading 2 styles:

C# insert and remove TOC from the word document

The below code snippet shows how to insert a Table of contents (TOC) into a document.

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Text.RegularExpressions;
namespace InsertTOC
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a new instance of Document and load the document from file.
            Document doc = new Document();
            doc.LoadFromFile("Sample.docx", FileFormat.Docx2010);

            //Add the TOC to the document
            TableOfContent toc = new TableOfContent(doc, "{\\o \"1-3\" \\h \\z \\u}");
            Paragraph p = doc.LastSection.Paragraphs[0];
            p.Items.Add(toc);
            p.AppendFieldMark(FieldMarkType.FieldSeparator);
            p.AppendText("TOC");
            p.AppendFieldMark(FieldMarkType.FieldEnd);
            doc.TOC = toc;

            //Update the table of contents
            doc.UpdateTableOfContents();

            //Save the document to file
            doc.SaveToFile("Result.docx", FileFormat.Docx);

        }
    }
}

C# insert and remove TOC from the word document

Removing a Table of Contents from the Document

using Spire.Doc;
using System.Text.RegularExpressions;
namespace RemoveTOC
{
    class Program
    {
        static void Main(string[] args)
        {
            //load the document from file with TOC 
            Document doc = new Document();
            doc.LoadFromFile("Result.docx", FileFormat.Docx2010);

            //get the first body from the first section
            Body body = doc.Sections[0].Body;

            //remove TOC from first body
            Regex regex = new Regex("TOC\\w+");
            for (int i = 0; i < body.Paragraphs.Count; i++)
            {
                if (regex.IsMatch(body.Paragraphs[i].StyleName))
                {
                    body.Paragraphs.RemoveAt(i);
                    i--;
                }
            }
            //save the document to file
            doc.SaveToFile("RemoveTOC.docx", FileFormat.Docx2010);

        }
    }
}

C# insert and remove TOC from the word document

How to update Ask Field in C#

2016-12-28 08:08:25 Written by support iceblue

With Spire.Doc for .NET, developers can easily operate the word fields from code. We have already shown how to create an IF field and remove Custom Property Fields in C#. From Spire.Doc V5.8.33, our developers add a new event UpdateFields to handle the Ask Field. This article will focus on demonstrating how to update the ASK field on the word document in C#.

Firstly, please view the sample document with an Ask filed which will be updated later:

How to update Ask Field in C#

Step 1: Create a new instance of Spire.Doc.Document class and load the document from file.

Document doc = new Document();
doc.LoadFromFile("Sample.docx");

Step 2: Call UpdateFieldsHandler event to update the ASK field.

doc.UpdateFields += new UpdateFieldsHandler(doc_UpdateFields);

Step 3: Update the fields in the document.

doc.IsUpdateFields = true;

Step 4: Save the document to file.

doc.SaveToFile("output.docx", FileFormat.Docx);

The following doc_UpdateFields () method shows how to update the ask field:

private static void doc_UpdateFields(object sender, IFieldsEventArgs args)
 {
     if (args is AskFieldEventArgs)
     {
         AskFieldEventArgs askArgs = args as AskFieldEventArgs;

         askArgs.ResponseText = "Female";
     }
 }

Effective screenshot after updating the Ask Field in C#:

How to update Ask Field in C#

Full codes:

using Spire.Doc;
using Spire.Doc.Fields;
namespace Askfield
{
    class Program
    {
        public void Field()
        {

            Document doc = new Document();
            doc.LoadFromFile("Sample.docx");

            doc.UpdateFields += new UpdateFieldsHandler(doc_UpdateFields);

            doc.IsUpdateFields = true;

            doc.SaveToFile("output.docx", FileFormat.Docx);

        }
        private static void doc_UpdateFields(object sender, IFieldsEventArgs args)
        {
            if (args is AskFieldEventArgs)
            {
                AskFieldEventArgs askArgs = args as AskFieldEventArgs;

                askArgs.ResponseText = "Female";
            }
        }


    }
}

In our daily work, we may have the requirement to add custom properties with fields to a Word document. As is shown in the following Word document, I have created three custom property fields for easily inserting or updating information.

How to Remove Custom Property Fields in C#, VB.NET

However, a custom property field may lose its value if we don’t want to use it any more, or a custom field might be created with wrong information, in such cases, we can choose to delete these fields manually and programmatically. In this article, I’ll introduce a C# and VB.NET solution to remove custom property fields using Spire.Doc.

Detailed Steps

Step 1: Create a new instance of Spire.Doc.Document class and load the sample file with specified path.

Document doc = new Document();
doc.LoadFromFile("FieldSample.docx", FileFormat.Docx);

Step 2: Get custom document properties object.

CustomDocumentProperties cdp = doc.CustomDocumentProperties;

Step 3: Use a for sentence and CustomDocumentProperties.Remove(string name) method to remove all custom property fields in the document.

for (int i = 0; i < cdp.Count; )
{
  cdp.Remove(cdp[i].Name);
}
doc.IsUpdateFields = true;

Step 4: Save the file.

doc.SaveToFile("Result.docx", FileFormat.Docx);

Output:

How to Remove Custom Property Fields in C#, VB.NET

Full Code:

C#
using Spire.Doc;
namespace RemoveProperties
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("FieldSample.docx", FileFormat.Docx);
            CustomDocumentProperties cdp = doc.CustomDocumentProperties;
            for (int i = 0; i < cdp.Count; )
            {
                cdp.Remove(cdp[i].Name);
            }
            doc.IsUpdateFields = true;
            doc.SaveToFile("Result.docx", FileFormat.Docx);
        }
    }
}
VB.NET
Imports Spire.Doc
Namespace RemoveProperties
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New Document()
			doc.LoadFromFile("FieldSample.docx", FileFormat.Docx)
			Dim cdp As CustomDocumentProperties = doc.CustomDocumentProperties
			Dim i As Integer = 0
			While i < cdp.Count
				cdp.Remove(cdp(i).Name)
			End While
			doc.IsUpdateFields = True
			doc.SaveToFile("Result.docx", FileFormat.Docx)
		End Sub
	End Class
End Namespace

How to create an IF field in C#

2014-08-28 01:17:09 Written by support iceblue

Usually we need to display different text and message to our readers based on the different conditions. In such situation, we need to create if field to decide which result to be displayed to readers. This article focuses on show you how to create an IF Field in C# with the help of Spire.Doc for .NET. We use the IF field and MERGEFIELD field together.

{IF { MERGEFIELD Count } > "100" "Thanks" "The minimum order is 100 units"}

Step 1: Create a new word document.

Document document = new Document();

Step 2: Add a new section for the document.

Section section = document.AddSection();

Step 3: Add a new paragraph for the section.

Paragraph paragraph = section.AddParagraph();

Step 4: Define a method of creating an IF Field.

CreateIfField(document, paragraph);

Step 5: Define merged data.

string[] fieldName = {"Count"};
string[] fieldValue = { "2" };

Step 6: Merge data into the IF Field.

document.MailMerge.Execute(fieldName, fieldValue);

Step 7: Update all fields in the document.

document.IsUpdateFields = true;

Step 8: Save the document to file.

document.SaveToFile("sample.docx", FileFormat.Docx);

The following CreateIfField() method shows how to create the IF Field like:

{IF { MERGEFIELD Count } > "100" "Thanks" " The minimum order is 100 units "}

static void CreateIfField(Document document, Paragraph paragraph)
{         
IfField ifField = new IfField(document);
ifField.Type = FieldType.FieldIf;
ifField.Code = "IF ";
paragraph.Items.Add(ifField);

paragraph.AppendField("Count",FieldType.FieldMergeField);
paragraph.AppendText(" > ");
paragraph.AppendText("\"100\" ");
paragraph.AppendText("\"Thanks\" ");
paragraph.AppendText("\"The minimum order is 100 units\"");

IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark);
(end as FieldMark).Type = FieldMarkType.FieldEnd;
paragraph.Items.Add(end);
ifField.End = end as FieldMark;
}

Check the effective screenshot as below:

How to create an IF field in C#

Full Code:

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Interface;
namespace CreatIF
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            Section section = document.AddSection();
            Paragraph paragraph = section.AddParagraph();
            CreateIfField(document, paragraph);
            string[] fieldName = { "Count" };
            string[] fieldValue = { "2" };

            document.MailMerge.Execute(fieldName, fieldValue);
            document.IsUpdateFields = true;
            document.SaveToFile("sample.docx", FileFormat.Docx);
        }

        static void CreateIfField(Document document, Paragraph paragraph)
        {
            IfField ifField = new IfField(document);
            ifField.Type = FieldType.FieldIf;
            ifField.Code = "IF ";
            paragraph.Items.Add(ifField);
            paragraph.AppendField("Count", FieldType.FieldMergeField);
            paragraph.AppendText(" > ");
            paragraph.AppendText("\"100\" ");
            paragraph.AppendText("\"Thanks\" ");
            paragraph.AppendText("\"The minimum order is 100 units\"");
            IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark);
            (end as FieldMark).Type = FieldMarkType.FieldEnd;
            paragraph.Items.Add(end);
            ifField.End = end as FieldMark;
        }

    }
}

We have already demonstrated how to create form field. This article mainly shows you how developers fill form field in word document in C# only with 4 simple steps by using a standalone .NET Word component Spire.Doc.

Make sure Spire.Doc for .NET has been installed correctly and then add Spire.Doc.dll as reference in the downloaded Bin folder thought the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll". Here comes to the details of how developers Fill Form Field by using Spire.Doc:

Step 1: Open the form that needs to fill the data.

[C#]
//Create word document
Document document = new Document(@"..\..\..\Data\UserForm.doc");

Step 2: Load data that will fill the form.

[C#]
//Fill data from XML file
using (Stream stream = File.OpenRead(@"..\..\..\Data\User.xml"))
{
    XPathDocument xpathDoc = new XPathDocument(stream);
    XPathNavigator user = xpathDoc.CreateNavigator().SelectSingleNode("/user");

Step 3: Use the loaded data to fill the form.

[C#]
//fill data
  foreach (FormField field in document.Sections[0].Body.FormFields)
  {
     String path = String.Format("{0}/text()", field.Name);
     XPathNavigator propertyNode = user.SelectSingleNode(path);
     if (propertyNode != null)
     {
         switch (field.Type)
         {
             case FieldType.FieldFormTextInput:
                  field.Text = propertyNode.Value;
                  break;

             case FieldType.FieldFormDropDown:
                  DropDownFormField combox = field as DropDownFormField;
                  for(int i = 0; i < combox.DropDownItems.Count; i++)
                  {
                      if (combox.DropDownItems[i].Text == propertyNode.Value)
                      {
                         combox.DropDownSelectedIndex = i;
                         break;
                      }
                      if (field.Name == "country" && combox.DropDownItems[i].Text == "Others")
                      {
                         combox.DropDownSelectedIndex = i;
                      }
                  }
                  break;

             case FieldType.FieldFormCheckBox:
                  if (Convert.ToBoolean(propertyNode.Value))
                  {
                      CheckBoxFormField checkBox = field as CheckBoxFormField;
                      checkBox.Checked = true;
                  }
                  break;
            }
       }
   }
 }

Step 4: Save the document to file in XML or Microsoft Word format.

[C#]
//Save doc file
document.SaveToFile("Sample.doc",FileFormat.Doc);

Effective Screenshot:

Fill FormField

Full Source Code for Fill FormField:

[C#]
namespace FillFormField
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //open form
            Document document = new Document(@"..\..\..\..\..\..\Data\UserForm.doc");

            //load data
            using (Stream stream = File.OpenRead(@"..\..\..\..\..\..\Data\User.xml"))
            {
                XPathDocument xpathDoc = new XPathDocument(stream);
                XPathNavigator user = xpathDoc.CreateNavigator().SelectSingleNode("/user");

                //fill data
                foreach (FormField field in document.Sections[0].Body.FormFields)
                {
                    String path = String.Format("{0}/text()", field.Name);
                    XPathNavigator propertyNode = user.SelectSingleNode(path);
                    if (propertyNode != null)
                    {
                        switch (field.Type)
                        {
                            case FieldType.FieldFormTextInput:
                                field.Text = propertyNode.Value;
                                break;

                            case FieldType.FieldFormDropDown:
                                DropDownFormField combox = field as DropDownFormField;
                                for(int i = 0; i < combox.DropDownItems.Count; i++)
                                {
                                    if (combox.DropDownItems[i].Text == propertyNode.Value)
                                    {
                                        combox.DropDownSelectedIndex = i;
                                        break;
                                    }
                                    if (field.Name == "country" && combox.DropDownItems[i].Text == "Others")
                                    {
                                        combox.DropDownSelectedIndex = i;
                                    }
                                }
                                break;

                            case FieldType.FieldFormCheckBox:
                                if (Convert.ToBoolean(propertyNode.Value))
                                {
                                    CheckBoxFormField checkBox = field as CheckBoxFormField;
                                    checkBox.Checked = true;
                                }
                                break;
                        }
                    }
                }
            }

            //Save doc file.
            document.SaveToFile("Sample.doc",FileFormat.Doc);

            //Launching the MS Word file.
            WordDocViewer("Sample.doc");
        }

        private void WordDocViewer(string fileName)
        {
            try
            {
                System.Diagnostics.Process.Start(fileName);
            }
            catch { }
        }

    }
}

A form allows you to create placeholders for different types of information, such as text, dates, images and yes-no questions. This makes it easier for readers to know what type of information to include, and it also helps ensure all of the information is formatted the same way. In order to create a fillable form in Word, you will need to use the following tools.

  • Content Controls: The areas where users input information in a form.
  • Tables: Tables are used in forms to align text and form fields, and to create borders and boxes.
  • Protection: Allows users to populate fields but not to make changes to the rest of the document.

Content controls in Word are containers for content that let users build structured documents. A structured document controls where content appears within the document. There are basically ten types of content controls available in Word 2013. This article focuses on how to create a fillable form in Word consisting of the following seven common content controls using Spire.Doc for .NET.

Content Control Description
Plain Text A text field limited to plain text, so no formatting can be included.
Rich Text A text field that can contain formatted text or other items, such as tables, pictures, or other content controls.
Picture Accepts a single picture.
Drop-Down List A drop-down list displays a predefined list of items for the user to choose from.
Combo Box A combo box enables users to select a predefined value in a list or type their own value in the text box of the control.
Check Box A check box provides a graphical widget that allows the user to make a binary choice: yes (checked) or no (not checked).
Date Picker Contains a calendar control from which the user can select a date.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Create a Fillable Form in Word in C# and VB.NET

The StructureDocumentTagInline class provided by Spire.Doc for .NET is used to create structured document tags for inline-level structures (DrawingML object, fields, etc.) in a paragraph. The SDTProperties property and the SDTContent property under this class shall be used to specify the properties and content of the current structured document tag. The following are the detailed steps to create a fillable form with content controls in Word.

  • Create a Document object.
  • Add a section using Document.AddSection() method.
  • Add a table using Section.AddTable() method.
  • Add a paragraph to a specific table cell using TableCell.AddParagraph() method.
  • Create an instance of StructureDocumentTagInline class, and add it to the paragraph as a child object using Paragraph.ChildObjects.Add() method.
  • Specify the properties and content of the structured document tag though the SDTProperties property and the SDTContent property of the StructureDocumentTagInline object. The type of the structured document tag is set through SDTProperties.SDTType property.
  • Prevent users from editing content outside form fields using Document.Protect() method.
  • Save the document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace CreateFormInWord
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document doc = new Document();

            //Add a section
            Section section = doc.AddSection();

            //add a table
            Table table = section.AddTable(true);
            table.ResetCells(7, 2);

            //Add text to the cells of the first column
            Paragraph paragraph = table.Rows[0].Cells[0].AddParagraph();
            paragraph.AppendText("Plain Text Content Control");
            paragraph = table.Rows[1].Cells[0].AddParagraph();
            paragraph.AppendText("Rich Text Content Control");
            paragraph = table.Rows[2].Cells[0].AddParagraph();
            paragraph.AppendText("Picture Content Control");
            paragraph = table.Rows[3].Cells[0].AddParagraph();
            paragraph.AppendText("Drop-Down List Content Control");
            paragraph = table.Rows[4].Cells[0].AddParagraph();
            paragraph.AppendText("Check Box Content Control");
            paragraph = table.Rows[5].Cells[0].AddParagraph();
            paragraph.AppendText("Combo box Content Control");
            paragraph = table.Rows[6].Cells[0].AddParagraph();
            paragraph.AppendText("Date Picker Content Control");

            //Add a plain text content control to the cell (0,1)
            paragraph = table.Rows[0].Cells[1].AddParagraph();
            StructureDocumentTagInline sdt = new StructureDocumentTagInline(doc);
            paragraph.ChildObjects.Add(sdt);
            sdt.SDTProperties.SDTType = SdtType.Text;
            sdt.SDTProperties.Alias = "Plain Text";
            sdt.SDTProperties.Tag = "Plain Text";
            sdt.SDTProperties.IsShowingPlaceHolder = true;
            SdtText text = new SdtText(true);
            text.IsMultiline = false;
            sdt.SDTProperties.ControlProperties = text;
            TextRange tr = new TextRange(doc);
            tr.Text = "Click or tap here to enter text.";
            sdt.SDTContent.ChildObjects.Add(tr);

            //Add a rich text content control to the cell (1,1)
            paragraph = table.Rows[1].Cells[1].AddParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.ChildObjects.Add(sdt);
            sdt.SDTProperties.SDTType = SdtType.RichText;
            sdt.SDTProperties.Alias = "Rich Text";
            sdt.SDTProperties.Tag = "Rich Text";
            sdt.SDTProperties.IsShowingPlaceHolder = true;
            text = new SdtText(true);
            text.IsMultiline = false;
            sdt.SDTProperties.ControlProperties = text;
            tr = new TextRange(doc);
            tr.Text = "Click or tap here to enter text.";
            sdt.SDTContent.ChildObjects.Add(tr);

            //Add a picture content control to the cell (2,1)
            paragraph = table.Rows[2].Cells[1].AddParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.ChildObjects.Add(sdt);
            sdt.SDTProperties.SDTType = SdtType.Picture;
            sdt.SDTProperties.Alias = "Picture";
            sdt.SDTProperties.Tag = "Picture";
            SdtPicture sdtPicture = new SdtPicture();
            sdt.SDTProperties.ControlProperties = sdtPicture;
            DocPicture pic = new DocPicture(doc);
            pic.LoadImage(Image.FromFile("C:\\Users\\Administrator\\Desktop\\ChooseImage.png"));
            sdt.SDTContent.ChildObjects.Add(pic);

            //Add a dropdown list content control to the cell(3,1)
            paragraph = table.Rows[3].Cells[1].AddParagraph();
            sdt = new StructureDocumentTagInline(doc);
            sdt.SDTProperties.SDTType = SdtType.DropDownList;
            sdt.SDTProperties.Alias = "Dropdown List";
            sdt.SDTProperties.Tag = "Dropdown List";
            paragraph.ChildObjects.Add(sdt);
            SdtDropDownList sddl = new SdtDropDownList();
            sddl.ListItems.Add(new SdtListItem("Choose an item.", "1"));
            sddl.ListItems.Add(new SdtListItem("Item 2", "2"));
            sddl.ListItems.Add(new SdtListItem("Item 3", "3"));
            sddl.ListItems.Add(new SdtListItem("Item 4", "4"));
            sdt.SDTProperties.ControlProperties = sddl;
            tr = new TextRange(doc);
            tr.Text = sddl.ListItems[0].DisplayText;
            sdt.SDTContent.ChildObjects.Add(tr);

            //Add two check box content controls to the cell (4,1)
            paragraph = table.Rows[4].Cells[1].AddParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.ChildObjects.Add(sdt);
            sdt.SDTProperties.SDTType = SdtType.CheckBox;
            SdtCheckBox scb = new SdtCheckBox();
            sdt.SDTProperties.ControlProperties = scb;
            tr = new TextRange(doc);
            sdt.ChildObjects.Add(tr);
            scb.Checked = false;
            paragraph.AppendText(" Option 1");

            paragraph = table.Rows[4].Cells[1].AddParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.ChildObjects.Add(sdt);
            sdt.SDTProperties.SDTType = SdtType.CheckBox;
            scb = new SdtCheckBox();
            sdt.SDTProperties.ControlProperties = scb;
            tr = new TextRange(doc);
            sdt.ChildObjects.Add(tr);
            scb.Checked = false;
            paragraph.AppendText(" Option 2");

            //Add a combo box content control to the cell (5,1)
            paragraph = table.Rows[5].Cells[1].AddParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.ChildObjects.Add(sdt);
            sdt.SDTProperties.SDTType = SdtType.ComboBox;
            sdt.SDTProperties.Alias = "Combo Box";
            sdt.SDTProperties.Tag = "Combo Box";
            SdtComboBox cb = new SdtComboBox();
            cb.ListItems.Add(new SdtListItem("Choose an item."));
            cb.ListItems.Add(new SdtListItem("Item 2"));
            cb.ListItems.Add(new SdtListItem("Item 3"));
            sdt.SDTProperties.ControlProperties = cb;
            tr = new TextRange(doc);
            tr.Text = cb.ListItems[0].DisplayText;
            sdt.SDTContent.ChildObjects.Add(tr);

            //Add a date picker content control to the cell (6,1)
            paragraph = table.Rows[6].Cells[1].AddParagraph();
            sdt = new StructureDocumentTagInline(doc);
            paragraph.ChildObjects.Add(sdt);
            sdt.SDTProperties.SDTType = SdtType.DatePicker;
            sdt.SDTProperties.Alias = "Date Picker";
            sdt.SDTProperties.Tag = "Date Picker";
            SdtDate date = new SdtDate();
            date.CalendarType = CalendarType.Default;
            date.DateFormat = "yyyy.MM.dd";
            date.FullDate = DateTime.Now;
            sdt.SDTProperties.ControlProperties = date;
            tr = new TextRange(doc);
            tr.Text = "Click or tap to enter a date.";
            sdt.SDTContent.ChildObjects.Add(tr);

            //Allow users to edit the form fields only
            doc.Protect(ProtectionType.AllowOnlyFormFields, "permission-psd");

            //Save to file
            doc.SaveToFile("WordForm.docx", FileFormat.Docx2013);
        }
    }
}

C#/VB.NET: Create a Fillable Form in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.