I just wanted to add more info why moving to a form field and inserting text using document buildes does not work and why you have to use strange looking FormField.NextSibling.NextSibling to do that.
The reason is that a complete form field in a Word document is a complex structure represented by several nodes: field start, field code such as FORMTEXT, form field data, field separator, field result, field end and a bookmark.
In a document tree the nodes are arranged like this:
- FieldStart - start
- BookmarkStart
- Run - field code such as " FORMTEXT "
-
FormField - contains ffdata
- FieldSeparator - separator
- Run - could be several, contain field value
- FieldEnd - field end
- BookmarkEnd
I’ve also seen this layout in some cases:
- BookmarkStart
- FieldStart - start
- Run - field code, one or more runs
- FormField
- FieldSeparator - separator
- Run - field value, one or more runs
- FieldEnd - field end
- BookmarkEnd
Using DocumentBuilder.MoveTo(FormField) moves the cursor to be before the FormField node. Then you use DocumentBuilder.Writeln(text) and that inserts text before the FormField node.
Therefore, the text is inserted into the field code. This is not a correct thing to do, you should not really have your text in the field code. Your text should be in the field result, that is between the FieldSeparator and FieldEnd nodes. Using FormField.NextSibling yelds the FieldSeparator node and using another NextSibling yelds the first node after the field separator. It is the correct place to insert text for you.
If this sounds complex, you should be using just FormField.Result = “MyText”. This method does just what I’ve described above.