Indeed, this would not work because when doing a simple mail merge, the document will be duplicated per each record. Why I asked you about the possibility of having the data in separate tables is because I thought that it would be possible to merge them into a single table where column names are prefixed with some unique identifier such as the name of the table they originate from. Then you could prepare merge fields in the template in a way like "TableName1_ColumnName1", "TableName1_Column2" and thus avoid the ambiguity.
I realize this approach is a bit clumsy and there is definitely a neater way to resolve; but I have tested it and it worked. I used code like the following:
[Test]
public void TestMailMerge()
{
Document doc = new Document("D:\\TestTableMerge.doc");
DataTable table1 = GetSampleDataTable("Table1");
DataTable table2 = GetSampleDataTable("Table2");
DataTable tableToMerge = new DataTable();
MergeTable(table1, tableToMerge);
MergeTable(table2, tableToMerge);
doc.MailMerge.Execute(tableToMerge);
doc.Save("D:\\TestTableMerge Out.doc");
}
private void MergeTable(DataTable srcTable, DataTable dstTable)
{
for (int i = 0; i < srcTable.Columns.Count; i++)
dstTable.Columns.Add(string.Format("{0}_{1}", srcTable.TableName, srcTable.Columns
.ColumnName));
for (int i = 0; i < srcTable.Rows.Count; i++)
{
DataRow row = GetOrAddRow(dstTable, i);
for (int j = 0; j < srcTable.Columns.Count; j++)
{
string dstColumnName = string.Format("{0}_{1}", srcTable.TableName, srcTable.Columns[j].ColumnName);
row[dstColumnName] = srcTable.Rows
[j];
}
}
}
private DataRow GetOrAddRow(DataTable table, int rowIndex)
{
if (rowIndex >= table.Rows.Count)
{
DataRow row = table.NewRow();
table.Rows.Add(row);
return row;
}
else
{
return table.Rows[rowIndex];
}
}
Let me know if you need any additional assistance on this inquiry.