Searching for MergeField with its name

Hello,

i want to move my DocumentBuilder to a specific MergeField in the document ro wirte with ListFormat at this position. Is there any posible way to search for this MergeField, using just its name?

And then use DocumentBuilder.MoveToField() to get to this MergeField, delete it and write my list.

I tried this:

DocumentBuilder.MoveToField(Document.GetChild("FieldName", true));

but the MoveToField Method does not support Strings as first parameter.

Greetings,

Crazkur

Edit:

i found a way, which is closer to working than my first try

Collection<Node> tmp = new Collection<Node>(Document.GetChildNodes(NodeType.Any, true).ToArray());
var node = tmp.First(n => n.GetText().Contains(fieldName));

_builder.MoveTo(node);

this throws me an System.InvalidOperationException at the Builder.MoveTo(node)
Additional information: The node must be a block or an inline.

Hi,

Thanks for your inquiry. The following code moves the cursor to a position just beyond the specified merge field and removes the merge field. It also starts a list and inserts some list item Paragraphs to it:

Document doc = new Document(MyDir + @"in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToMergeField("mf");
builder.ListFormat.List = doc.Lists.Add(ListTemplate.NumberArabicDot);
builder.Writeln("first item");
builder.Writeln("second item");
builder.Writeln("third item");
doc.Save(MyDir + @"17.1.0.docx");

Hope, this helps.

Best regards,

Hi Awais,

thanks for your answer. This works great

Is there also a possibility to move my DocumentBuilder to a MergeField without deleting it?
Or at least a workaround for that?

Greetings,

Crazkur

Hi,

Thanks for your inquiry. Please use following overload of DocumentBuilder.MoveToMergeField method:

  • DocumentBuilder.MoveToMergeField Method (String, Boolean, Boolean)
Document doc = new Document(MyDir + @"in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToMergeField("mf", true, false);
builder.Writeln();
builder.ListFormat.List = doc.Lists.Add(ListTemplate.NumberArabicDot);
builder.Writeln("first item");
builder.Writeln("second item");
builder.Writeln("third item");
doc.Save(MyDir + @"17.1.0.docx");

Hope, this helps.

Best regards,

Works perfectly

Many thanks to you.