Free Support Forum - aspose.com

Accessing datatable from mergefield event

Hi,

is there any way to access the current datarow and/or the datatable from within the mergefieldevent

Hi<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your inquiry. There is no direct way to achieve this. From MergeField event handler you can get only index of current record in data source. If you need to get data source then you can try using the following code:

public void Test031()

{

//Create dataTable

DataTable tab = new DataTable("myTable");

tab.Columns.Add("Field1");

tab.Columns.Add("Field2");

tab.Columns.Add("Field3");

//Add some data

tab.Rows.Add(new object[] { "first1", "first2", "first3" });

tab.Rows.Add(new object[] { "second1", "second2", "second3" });

tab.Rows.Add(new object[] { "third1", "third2", "third3" });

//Open template

Document doc = new Document(@"Test031\in.doc");

CustumMailMerge mm = new CustumMailMerge(doc);

mm.ExecuteWithRegions(tab);

doc.Save(@"Test031\out.doc");

}

class CustumMailMerge

{

///

/// Cinstroctor. Adds MergeFueldEvent

///

public CustumMailMerge(Document doc)

{

mDocument = doc;

//Add MergeField event handler

mDocument.MailMerge.MergeField += new MergeFieldEventHandler(MailMerge_MergeField);

}

///

/// MergeField Event handler

///

void MailMerge_MergeField(object sender, MergeFieldEventArgs e)

{

//Here we can access to datasource

//For example we can get current row

DataRow currentRow = mDataSource.Rows[e.RecordIndex];

//Do something

}

///

/// ExecuteWithRegions method

///

public void ExecuteWithRegions(DataTable ds)

{

mDataSource = ds;

mDocument.MailMerge.ExecuteWithRegions(ds);

}

//Private fields

private Document mDocument = new Document();

private DataTable mDataSource = new DataTable();

}

I hope this could help you

Best regards.