Free Support Forum - aspose.com

Aspose.Words insert nested fields programmatically

I need to insert nested fields programmatically. Here is a sample:

{ IF { MERGEFIELD MY_FIELD } = TRUE { MERGEFIELD MY_TRUE } { MERGEFIELD MY_FALSE } }

or

{ = { PAGE } \# 00 }

One way of inserting fields is to use DocumentBuilder.InsertField(""). But this API is not enough to insert the nested Field. Could you please direct me to an API I could use or a workaround.

Hi there,

Thanks for your inquiry.

You can use the code like below to insert fields nested with an IF field.

Document doc = new Document();

DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a few page breaks (just for testing)

for (int i = 0; i < 5; i++)

builder.InsertBreak(BreakType.PageBreak);

// Move the DocumentBuilder cursor into the primary footer.

builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);

// We want to insert a field like this:

// { IF {PAGE} <> {NUMPAGES} "See Next Page" "Last Page" }

Field field = builder.InsertField(@"IF ");

builder.MoveTo(field.Separator);

builder.InsertField("PAGE");

builder.Write(" <> ");

builder.InsertField("NUMPAGES");

builder.Write(" \"See Next Page\" \"Last Page\" ");

// Finally update the outer field to recalcaluate the final value. Doing this will automatically update

// the inner fields at the same time.

field.Update();


Thanks,