Back to Devexpress

How to: Validate the ObjectDataSource Contained in the Spreadsheet MailMerge Template

officefileapi-118757-spreadsheet-document-api-examples-mail-merge-how-to-validate-the-object-data-source-contained-in-the-spreadsheet-mail-merge-template.md

latest3.0 KB
Original Source

How to: Validate the ObjectDataSource Contained in the Spreadsheet MailMerge Template

  • Sep 25, 2023
  • 2 minutes to read

Loading the mail merge templates with the ObjectDataSource data source may cause undesired behavior if the data source is contained in a compiled assembly. This example illustrates how to use a custom service that implements the IObjectDataSourceValidationService interface to validate an ObjectDataSource contained in the loaded mail merge template and prevent the data source from loading.

csharp
public class MyObjectDataSourceValidationService : IObjectDataSourceValidationService {
    public void Validate(IEnumerable<ObjectDataSource> dataSources)
    {
        // Do nothing to allow the control to load data.
        // Clear the DataSource and DataMember properties to prohibit data loading.
        foreach (ObjectDataSource ds in dataSources)
        {
            if (ds.Name != "EmployeeDS")
            {
                ds.DataSource = null;
                ds.DataMember = null;
            }
        };
    }
}
vb
Public Class MyObjectDataSourceValidationService
    Implements IObjectDataSourceValidationService

    Public Sub Validate(ByVal dataSources As IEnumerable(Of ObjectDataSource)) Implements IObjectDataSourceValidationService.Validate
        ' Do nothing to allow the control to load data.
        ' Clear the DataSource and DataMember properties to prohibit data loading.
        For Each ds As ObjectDataSource In dataSources
            If ds.Name <> "EmployeeDS" Then
                ds.DataSource = Nothing
                ds.DataMember = Nothing
            End If
        Next ds
    End Sub
End Class
csharp
using DevExpress.Spreadsheet;
using System.Diagnostics;
static void Main()
{
    Workbook workbook = new Workbook();
    workbook.ReplaceService<IObjectDataSourceValidationService>(new MyObjectDataSourceValidationService());
    workbook.LoadDocument("EmployeesMailMergeTemplate.xlsx");
    var result = workbook.GenerateMailMergeDocuments();
    result[0].SaveDocument("result.xlsx");
    Process.Start("result.xlsx");
}
vb
Imports DevExpress.Spreadsheet
Imports System.Diagnostics

Shared Sub Main()
    Dim workbook As Workbook = Workbook()
    workbook.ReplaceService(Of IObjectDataSourceValidationService)(New MyObjectDataSourceValidationService())
    workbook.LoadDocument("EmployeesMailMergeTemplate.xlsx")
    Dim result = workbook.GenerateMailMergeDocuments()
    result(0).SaveDocument("result.xlsx")
    Process.Start("result.xlsx")
End Sub