Conditionally show/hide data in C# .NET .docx Word Report Templates
Tags: webdev, devops, csharp, tutorial
Published: 2023-08-02 19:57:19

---
canonical_url: https://developer.mescius.com/blogs/conditionally-show-hide-data-in-c-sharp-net-docx-word-report-templates
description: Learn how to conditionally show/hide data in C# .NET .docx Word report templates. See more from GrapeCity today.
---
Although organizations of all types use complex reporting, and many utilize Microsoft Word documents as the file of choice, it is unnecessary to recreate complex reports from scratch each time. Instead, it's better to use a template approach, many of which are standardized in various industries and organizations.

Once a templated approach in a Word .docx file has been established, it is easy with [GrapeCity Documents for Word](https://developer.mescius.com/document-solutions/dot-net-word-api) (GcWord) API to bind data to the word .docx template, creating dynamic, complex, and flexible Word .docx format reports using [GcWord Templates feature](https://developer.mescius.com/document-solutions/dot-net-word-api/report-templates). The API saves the Word reports as .docx files, PDF files, or images. Developers can create a Word template using the mustache syntax to define the database fields, variables, bullets, lists, multi-level lists, and tables. This formatting makes it easy to replace the templated fields (those notated in mustache format).

A data source is added by using the **GcWordDocument.DataTemplate.DataSources** collection and binding the data with the template using the **GcWordDocument.DataTemplate.Process()** method. This template API will detect the fields, match them with the appropriate data in the database and replace them with the actual data. There is also an option for batch processing through the **DataTemplate.BatchProcess()** method to generate a data-bound copy of the document for each iterated data object without changing the current document.

The following is a snapshot of a Closing Disclosure Word Template and the resulting Word Report upon processing the template:

![C# .docx](https://files.grapecity.com/gc-website-media/hhhjgmkf/01-template.png?width=500&height=291.2785774767147)

### Generate the following reports:

*   Legal
*   Employee Contracts
*   House Lease Agreements
*   Invoices
*   Flight ticket
*   Itinerary
*   Price catalogs
*   And more

Have a look at this tutorial to see [how to bind Word Report Templates with the database using GcWord Report Templates feature](https://developer.mescius.com/document-solutions/dot-net-word-api/docs/online/generate-document-using-data-templates.html).

### Conditionally show/hide data in Word Report Templates .docx using C# .NET

Often in data-bound Word reports, especially Legal or Consulting Agreement Contracts, some clauses need to be hidden depending on who the viewer of the document is. Or certain sections need to be shown if only certain conditions are true upon processing the template.

[GcWord Report Templates](https://developer.mescius.com/document-solutions/dot-net-word-api/report-templates) supports **‘if/else/endif’** statements to define conditions to simultaneously show/hide whole block or multiple blocks. The condition defined is a set of template value operands combined with arithmetic or logic operations.

Consider the following example, which shows or hides retainer information from a Consulting Agreement document with a single if/endif condition (shows retainer information if payRetainer=1). This is an alternative and easier method than hiding specific blocks using [**hbi**](https://developer.mescius.com/document-solutions/dot-net-word-api/docs/online/conditionally-hide-blocks.html) statements. Also, hbi will only hide a specific line, but if/else/endif statements can show/hide multiple lines.

To achieve this, set the if/endif condition in the Word Template file -

```
    {{if (payRetainer)}}
    {{retainerAmount}:format(C)}
    A retainer of {{retainerAmount}:format(C)} (the "Retainer") is payable by the Client upon execution of this Agreement.
    {{endif}}
```

The Word Template would look like this:

![C# .docx](https://files.grapecity.com/gc-website-media/azgm25on/02-conditional.png?width=500&height=301.8118245390973)

Import this Word Template file in GcWord, bind it with data, process the template, and save it to a .docx file.

```
    var doc = new GcWordDocument();
    doc.Load("Consulting_Agreement_Template.docx");
    using (var ds = new DataSet())
    {
        ds.ReadXml("GcWordTplDataSet.xml");
        doc.DataTemplate.DataSources.Add("ds", ds.Tables[0]);
        doc.DataTemplate.Process();
        doc.Save("ConsultingAgreement.docx");

    }
```

Have a look at the following screenshot. In the data, payRetainer is turned off, so the clause for the retainer amount to be paid is not displayed.

![C# .docx](https://files.grapecity.com/gc-website-media/aziibppe/03-conditionaltemplate.png?width=500&height=272.42152466367713)

#### Show products with a price greater than $50

Also, check out [the sample](https://developer.mescius.com/document-solutions/dot-net-word-api/demos/report-templates/data-tpl-product-if/code-cs) where Products only with a Price greater than $50 are shown in the Table. To achieve this, you can also include the if/else/endif statements in the code.

The code below uses report templates' conditional construct '{ {if...} }..{ {else} }..{ {endif} } to filter data so that only products with a price greater than $50 are included. If the first column of a table starts with '{ {if...} }' and ends with '{ {endif} }', empty rows added as the result of template expansion will be removed.

```
    var caption0 = "Product List";
    var caption1 = $"Products that cost more than $50";
    var pStart0 = @"{{#ds}}{{ds.ProductID}}";
    var pEnd0 = @"{{/ds}}";
    // NOTE: for empty rows to be automatically removed, the first cell in the template row
    // must start with {{if ...}}, and the last cell must end with matching {{endif}}:
    var pStart1 = @"{{if ds.UnitPrice > 50}}{{ds.ProductID}}";
    var pEnd1 = @"{{endif}}";

    doc.Body.Replace(caption0, caption1);
    doc.Body.Replace(pEnd0, pEnd1);
    doc.Body.Replace(pStart0, pStart1);
```

Load the data set and bind the Word template with data. Process the template and save the Word file.

```
    using (var ds = new DataSet())
    {
                    // Load data and build the product list data source:
                    ds.ReadXml(Path.Combine("Resources", "data", "GcNWind.xml"));

                    DataTable dtProds = ds.Tables["Products"];
                    DataTable dtSupps = ds.Tables["Suppliers"];

                    var products =
                        from prod in dtProds.Select()
                        join supp in dtSupps.Select()
                        on prod["SupplierID"] equals supp["SupplierID"]
                        orderby prod["UnitPrice"] descending
                        select new
                        {
                            ProductID = prod["ProductID"],
                            ProductName = prod["ProductName"],
                            Supplier = supp["CompanyName"],
                            QuantityPerUnit = prod["QuantityPerUnit"],
                            UnitPrice = prod["UnitPrice"]
                        };

                    // Add the data source to the data template data sources:
                    doc.DataTemplate.DataSources.Add("ds", products);

                    // Process the template:
                    doc.DataTemplate.Process();
    }
    doc.Save("ProductList.docx");
```

Here is what the Word report looks like:

![C# .docx](https://files.grapecity.com/gc-website-media/ppzpbajm/04-productlist.png?width=500&height=291.98419418571837)

For a complete sample, visit this [link](https://developer.mescius.com/document-solutions/dot-net-word-api/demos/report-templates/data-tpl-product-if/code-cs).

Visit the following links to learn more about features supported with [GcWord Templates](https://developer.mescius.com/document-solutions/dot-net-word-api/report-templates).

*   [Documentation](https://developer.mescius.com/document-solutions/dot-net-word-api/docs/online/data-templates.html)
*   [Demo](https://developer.mescius.com/document-solutions/dot-net-word-api/demos/report-templates)

We hope you like this feature. Share your use cases where you would like to use if/else/endif statements in your Word .docx Templates. Leave your comments below.