Overwrite field content

85 Views Asked by At

I am using this code to put content in a Field using Word Interop:

var wordApp = new Microsoft.Office.Interop.Word.Application();
var wordDoc = wordApp.Documents.Add(Path.GetFullPath("myTemplate.dotx"));
Field f = wordDoc.Fields[0];
f.Select();
wordApp.Selection.TypeText("some text");

but this works only once. If I run the f.Select() statement again, I get a COMException telling me the object is gone.

Is there a way to overwrite field content? Or do I have to work with being able to write a Field only once?

1

There are 1 best solutions below

0
On BEST ANSWER

When you select the field, and then use TypeText, that replaces the whole field with your input text. Instead, you should be using Field.Result property:

f.Result.Text = "some text";

Therefore, your code should be something like the following:

var wordApp = new Microsoft.Office.Interop.Word.Application();
var wordDoc = wordApp.Documents.Add(Path.GetFullPath("myTemplate.dotx"));
wordDoc.Fields[1].Result.Text = "some text"; // AFAIK, `Fields` collection is one-based.

// Do whatever other modifications you want, then save and close the document.

Hope that helps :)