Word merge event handler in C#, VB.NET

  • Demo
  • C# source
  • VB.Net source

The sample demonstrates how to handle merge event.

public partial class Form1 : Form
{
    private int lastIndex = 0;
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //Create word document
        Document document = new Document();
        document.LoadFromFile(@"..\..\..\..\..\..\Data\Fax2.doc");
        lastIndex = 0;

        List<CustomerRecord> customerRecords = new List<CustomerRecord>();
        CustomerRecord c1 = new CustomerRecord();
        c1.ContactName = "Lucy";
        c1.Fax = "786-324-10";
        c1.Date = DateTime.Now;
        customerRecords.Add(c1);

        CustomerRecord c2 = new CustomerRecord();
        c2.ContactName = "Lily";
        c2.Fax = "779-138-13";
        c2.Date = DateTime.Now;
        customerRecords.Add(c2);

        CustomerRecord c3 = new CustomerRecord();
        c3.ContactName = "James";
        c3.Fax = "363-287-02";
        c3.Date = DateTime.Now;
        customerRecords.Add(c3);

        //Execute mailmerge
        document.MailMerge.MergeField += new MergeFieldEventHandler(MailMerge_MergeField);
        document.MailMerge.ExecuteGroup(new MailMergeDataTable("Customer", customerRecords));

        //Save doc file.
        document.SaveToFile(@"Sample.doc", FileFormat.Doc);
    }

    void MailMerge_MergeField(object sender, MergeFieldEventArgs args)
    {
        //Next row
        if (args.RowIndex > lastIndex)
        {
            lastIndex = args.RowIndex;
            AddPageBreakForMergeField(args.CurrentMergeField);
        }
    }

    void AddPageBreakForMergeField(IMergeField mergeField)
    {
        //Find position of needing to add page break
        bool foundGroupStart = false;
        Paragraph paramgraph = mergeField.PreviousSibling.Owner as Paragraph;
        MergeField merageField = null;
        while (!foundGroupStart)
        {
            paramgraph = paramgraph.PreviousSibling as Paragraph;
            for (int i = 0; i < paramgraph.Items.Count; i++)
            {
                merageField = paramgraph.Items[i] as MergeField;
                if ((merageField != null) && (merageField.Prefix == "GroupStart"))
                {
                    foundGroupStart = true;
                    break;
                }
            }
        }

        paramgraph.AppendBreak(BreakType.PageBreak);
    }
}

public class CustomerRecord
{
    private string m_contactName;
    public string ContactName
    {
        get
        {
            return m_contactName;
        }
        set
        {
            m_contactName = value;
        }
    }

    private string m_fax;
    public string Fax
    {
        get
        {
            return m_fax;
        }
        set
        {
            m_fax = value;
        }
    }

    private DateTime m_date;
    public DateTime Date
    {
        get
        {
            return m_date;
        }
        set
        {
            m_date = value;
        }
    }
}

	Public Partial Class Form1
		Inherits Form
		Private lastIndex As Integer = 0
		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub button1_Click(sender As Object, e As EventArgs)
			'Create word document
			Dim document As New Document()
			document.LoadFromFile("..\..\..\..\..\Data\Fax2.doc")
			lastIndex = 0

			Dim customerRecords As New List(Of CustomerRecord)()

			Dim c1 As New CustomerRecord()
			c1.ContactName = "Lucy"
			c1.Fax = "786-324-10"
			c1.[Date] = DateTime.Now
			customerRecords.Add(c1)

			Dim c2 As New CustomerRecord()
			c2.ContactName = "Lily"
			c2.Fax = "779-138-13"
			c2.[Date] = DateTime.Now
			customerRecords.Add(c2)

			Dim c3 As New CustomerRecord()
			c3.ContactName = "James"
			c3.Fax = "363-287-02"
			c3.[Date] = DateTime.Now
			customerRecords.Add(c3)

			'Execute mailmerge
			document.MailMerge.MergeField += New MergeFieldEventHandler(AddressOf MailMerge_MergeField)
			document.MailMerge.ExecuteGroup(New MailMergeDataTable("Customer", customerRecords))

			'Save doc file.
			document.SaveToFile("Sample.doc", FileFormat.Doc)
		End Sub

		Private Sub MailMerge_MergeField(sender As Object, args As MergeFieldEventArgs)
			'Next row
			If args.RowIndex > lastIndex Then
				lastIndex = args.RowIndex
				AddPageBreakForMergeField(args.CurrentMergeField)
			End If
		End Sub

		Private Sub AddPageBreakForMergeField(mergeField As IMergeField)
			'Find position of needing to add page break
			Dim foundGroupStart As Boolean = False
			Dim paramgraph As Paragraph = TryCast(mergeField.PreviousSibling.Owner, Paragraph)
			Dim merageField As MergeField = Nothing
			While Not foundGroupStart
				paramgraph = TryCast(paramgraph.PreviousSibling, Paragraph)
				For i As Integer = 0 To paramgraph.Items.Count - 1
					merageField = TryCast(paramgraph.Items(i), MergeField)
					If (merageField IsNot Nothing) AndAlso (merageField.Prefix = "GroupStart") Then
						foundGroupStart = True
						Exit For
					End If
				Next
			End While

			paramgraph.AppendBreak(BreakType.PageBreak)
		End Sub
	End Class

	Public Class CustomerRecord
		Private m_contactName As String
		Public Property ContactName() As String
			Get
				Return m_contactName
			End Get
			Set
				m_contactName = value
			End Set
		End Property

		Private m_fax As String
		Public Property Fax() As String
			Get
				Return m_fax
			End Get
			Set
				m_fax = value
			End Set
		End Property

		Private m_date As DateTime
		Public Property [Date]() As DateTime
			Get
				Return m_date
			End Get
			Set
				m_date = value
			End Set
		End Property
	End Class
End Namespace