Free Support Forum - aspose.com

Table Databinding and Removing Paragraphs of Text

Hi all,

I have a scenario that I'd appreciate some guidance on, I wonder if anyone has any advice? :)

We're using the .MailMerge.ExecutewithRegions() method to bind data to the document however I have a requirement to remove certain paragraphs based on the Rows of Data.

Is this possible, if so how would you go about doing it?

Let's say I have the following: -

«TableStart:Products»Mortgage Account «AccountNumber»<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Paragraph1

Paragraph2

Paragraph3

«TableEnd:Products»

In some circumstances (dictated by a flag in the Row of Data) I'd like Paragraph2 to be deleted.

How would you go about this?

Cheers,

Phil.

Hello

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your request. I think in your case you can try using FieldMergingCallback, please see the following link to learn more:

http://www.aspose.com/documentation/.net-components/aspose.words-for-.net/aspose.words.reporting.ifieldmergingcallback.html

Please see the following code:

// Create data table

DataTable table = new DataTable("Products");

table.Columns.Add("AccountNumber");

// Add some dummy data.

table.Rows.Add(new object[] { "AccountNumber1" });

table.Rows.Add(new object[] { "AccountNumber2" });

table.Rows.Add(new object[] { "AccountNumber3" });

table.Rows.Add(new object[] { "AccountNumber4" });

//Open template document

Document doc = new Document("in.docx");

// Add merge field event handler

doc.MailMerge.FieldMergingCallback = new RemoveParagraphMergingCallback();

doc.MailMerge.ExecuteWithRegions(table);

doc.Save("out.docx");

private class RemoveParagraphMergingCallback : IFieldMergingCallback

{

void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)

{

if (args.FieldValue.ToString() == "AccountNumber3")

{

// We need to get second paragraph

Paragraph paragraph1 = (Paragraph)args.Field.End.NextPreOrder(args.Document);

Paragraph paragraph2 = (Paragraph)paragraph1.NextSibling;

paragraph2.Remove();

}

}

void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)

{

// Do nothing.

}

}

The input and the output documents are attached.

Best regards,