Our shipped mail merge and database samples for TX Text Control .NET for Windows Forms use an XML database to keep things simple. But we are getting more and more requests for a sample that shows how to realize a mail merge application with a Microsoft SQL Server database.

Generally, the approach is quite similar: You need to loop through all merge fields in order to merge the specific values of the database columns. In this sample, the adapter fields of the DocumentServer namespace are used. These adapter fields can be used to create and manipulate specific ApplicationField objects without changing the ApplicationField.Parameters manually.

The following code is used for the underlying merge process:

// [C#]
foreach (TXTextControl.ApplicationField field in tx.ApplicationFields)
{
    try
    {
        if (field.TypeName != "MERGEFIELD")
            return;

        // create a new field adapter
        TXTextControl.DocumentServer.Fields.MergeField mf =
            new TXTextControl.DocumentServer.Fields.MergeField(field);

        if (this.customersDataSet.customers.Columns.Contains(mf.Name) == false)
            continue;

        // merge the text
        field.Text = this.customersDataSet.customers.Rows[
            dataGridView1.SelectedRows[0].Index][mf.Name].ToString();
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}

The sample project comes with a sample MS SQL Server database file. Using the same approach, you can connect to your SQL Server database tables to merge database content into MS Word compatible templates.

Download the Visual Studio 2008 C# project and test it on your own. At minimum, you need a TX Text Control .NET for Windows Forms 15.1 trial version and a Microsoft SQL Express edition (2005 or 2008).

tx_sql_db.zip