Delete/Remove empty tables from doc after ExecuteWithRegions in C#

RemoveEmptyTables.GIF (22.7 KB)

Remove or delete empty table from doc after ExecuteWithRegions is performed in C#

@shubham98 You can use MailMergeCleanupOptions.RemoveEmptyTableRows and MailMergeCleanupOptions.RemoveUnusedRegions to remove empty row and unused regions in your template appropriately.

But it would be better if you attach your sample template, data, current and expected output documents. This will help us to better understand your template structure. Unfortunately, screenshot does not allow to analyze the issue.

Hi alexey,

thanks for quick response , i have attached the template.
I want to delete/remove the table itself with the headers when rows are blank,
the table should not be visible if it is empty table.
PrivateVisitToAbroad11.docx (3.4 MB)

@shubham98 Thank you for additional information. In your case it is required to remove two rows from the table but not the whole table. I am afraid, there is no built in method to achieve this.
However, you can achieve this by postprocessing the document and removing empty rows from the table along with the previous row (header row). For example see the following code:

// Empty tables in data source
DataSet ds = new DataSet();
DataTable dt1 = new DataTable("family");
dt1.Columns.Add("SrNo");

DataTable dt2 = new DataTable("visits");
dt2.Columns.Add("pot");

ds.Tables.Add(dt1);
ds.Tables.Add(dt2);

Document doc = new Document(@"C:\Temp\in.docx");
doc.MailMerge.ExecuteWithRegions(ds);
// Remove not filled regions along with header rows.
List<FieldMergeField> regionStarts = doc.Range.Fields.Where(f => f.Type == FieldType.FieldMergeField)
    .Cast<FieldMergeField>().Where(f => f.FieldName.ToLower().StartsWith("tablestart")).ToList();

foreach (FieldMergeField mf in regionStarts)
{
    // get parent row.
    Row r = (Row)mf.Start.GetAncestor(NodeType.Row);
    if (r != null)
    {
        // Remove row and previous row.
        if (r.PreviousSibling != null)
            r.PreviousSibling.Remove();
        r.Remove();
    }
}

doc.Save(@"C:\Temp\out.docx");

Hi alexey,

i am afraid that there is some misunderstanding, i want to remove the whole table if there is no rows in a table (i.e. blank table)
i have attached before and after how it should look.
RemoveEmptyTables.GIF (22.7 KB)

After.GIF (15.9 KB)

@shubham98 The provided code does exactly this. Please see the attached output produced by the above code:
out.docx (3.9 MB)