AlternatingRows.cs
//
// This code is part of GrapeCity Documents for Word samples.
// Copyright (c) GrapeCity, Inc. All rights reserved.
//
using System;
using System.IO;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using GrapeCity.Documents.Word;

namespace GcWordWeb.Samples
{
    // This sample uses conditional table formatting to build a table
    // with alternating row backgrounds.
    public class AlternatingRows
    {
        public GcWordDocument CreateDocx()
        {
            GcWordDocument doc = new GcWordDocument();

            // Random-ish table dimensions:
            var rand = new Random((int)DateTime.Now.Ticks);
            var rows = rand.Next(10, 100);
            var cols = rand.Next(4, 6);

            var section = doc.Body.Sections.First;
            section.GetRange().Paragraphs.Add(
                $"A {cols} columns by {rows} rows table, with conditional styles applied to alternating rows:");

            // Add an empty table:
            var t = section.GetRange().Tables.Add(0, 0);

            // Add some rows and cells to it:
            var cells = new List<string>(cols);
            for (int col = 0; col < cols; ++col)
                cells.Add(string.Empty);
            for (int row = 0; row < rows; ++row)
            {
                for (int col = 0; col < cols; ++col)
                    cells[col] = $"Row {row + 1}, col {col + 1}";
                t.Rows.Add(cells.ToArray());
            }

            // Create a table style on which we will define conditional formatting:
            var ts1 = doc.Styles.Add("Table Style 1", StyleType.Table);
            // And assign the style to the table:
            t.Style = ts1;

            // Set up simple borders:
            foreach (var border in ts1.Table.Borders)
            {
                border.LineStyle = LineStyle.Single;
                border.LineWidth = 0.5f;
                border.Color.RGB = Color.DarkGray;
            }
            // Add some padding:
            ts1.Table.Padding.All = 2;

            // To use certain table styles, we need to set corresponding flags on the table's style options:
            t.Format.StyleOptions = TableStyleOptions.RowBands;

            // Set up the style to use alternating background colors on odd and even rows:
            ts1.Table.RowStripe = 1;
            // Odd rows' style:
            ts1.Table.Conditionals[TableStyleOverride.Band1Horizontal].Shading.Texture = TexturePattern.Clear;
            ts1.Table.Conditionals[TableStyleOverride.Band1Horizontal].Shading.BackgroundPatternColor.RGB = Color.FromArgb(0xe6, 0xff, 0xe6);
            // Even rows' style:
            ts1.Table.Conditionals[TableStyleOverride.Band2Horizontal].Shading.Texture = TexturePattern.Clear;
            ts1.Table.Conditionals[TableStyleOverride.Band2Horizontal].Shading.BackgroundPatternColor.RGB = Color.FromArgb(0xff, 0xff, 0xe6);

            // Done:
            return doc;
        }
    }
}