邮件合并功能与之前的提到的将TX文档全部存入数据库有所不同,邮件合并功能是将数据库中特定字段插入到模板文档的特定位置。与此同时,本章节还会演示在邮件合并功能的基础上添加打印功能、以及如何创建邮件合并所需的模板文档。
本章节相应的源代码可以在TX Text Control.NET的安装目录中找到: Samples\WinForms\VB.NET\MailMerge Samples\WinForms\CSharp\MailMerge 第一步:合并数据库数据和文本 启动程序并选择Template菜单下的Load命令,通过Load命令加载模板文件,模板文件中包含一些文本域,这些文本域的数据将被数据库中对应的数据替换。![](http://static.oschina.net/uploads/img/201406/11120839_KSvM.jpg)
![](http://static.oschina.net/uploads/img/201406/11120840_IqSP.jpg)
![](http://static.oschina.net/uploads/img/201406/11120840_9RWf.jpg)
[C#] private void GetRecord() { DataRow Row = dsAddress.Tables[0].Rows[CurrentRow]; lblCompany.Text = Row["company"].ToString(); lblRecipient.Text = Row["recipient"].ToString(); lblStreet.Text = Row["street"].ToString(); lblCity.Text = Row["city"].ToString(); lblCountry.Text = Row["country"].ToString(); lblSalutation.Text = Row["salutation"].ToString(); SetButtonState(); }
点击【Merge】按钮时,数据源中的数据将被拷贝到文档的相应的文本域中,文本域与数据源中的字段有着相同名字,所以通过For Each操作可以完成这个拷贝工作:
[C#] private void cmdMerge_Click(object sender, System.EventArgs e) { foreach (TXTextControl.TextField Field in tx.TextFields) { Field.Text = dsAddress.Tables[0].Rows[CurrentRow][Field.Name].ToString(); } }
第二步:打印操作
在【Address Database】窗体中添加一个【Print】按钮,当点击【Print】按钮时,程序会将数据源中的记录合并到文档中并进行打印操作:
[C#] private void cmdPrint_Click(object sender, System.EventArgs e) { PrintDocument PrintDoc = new PrintDocument(); foreach (DataRow CurrentRow in dsAddress.Tables[0].Rows) { // Merge data from current record foreach (TXTextControl.TextField Field in tx.TextFields) Field.Text = CurrentRow[Field.Name].ToString(); // Print PrintDoc.PrinterSettings.FromPage = 0; PrintDoc.PrinterSettings.ToPage = tx.Pages; tx.Print(PrintDoc); } }
由于打印操作会自动将数据进行合并,所以不再需要步骤一中的【Merge】按钮,同时使用Grid来显示数据源中的数据,这样可以更好的浏览数据源中的数据
![](http://static.oschina.net/uploads/img/201406/11120840_DBeL.jpg)
[C#] private void mnuFile_SaveTemplateAs_Click(object sender, System.EventArgs e) { dlgSaveFile.Filter = "Text Control Files (*.tx)|*.tx"; dlgSaveFile.ShowDialog(); if (dlgSaveFile.FileName != "") textControl1.Save(dlgSaveFile.FileName, TXTextControl.StreamType.InternalFormat); }
添加数据库字段
第一和第二步中包含了必须的文本域,为了创建更灵活的文件,应用程序应该提供给用户选择数据库字段的功能,由用户来决定将哪些字段添加到模板文档中。在程序中添加一个【Insert】菜单,菜单包含数据源中的所有列:![](http://static.oschina.net/uploads/img/201406/11120840_foA4.jpg)
[C#] private void CreateTextFieldMenu() { mnuInsert.MenuItems.Clear(); foreach (DataColumn DataField in dsAddress.Tables[0].Columns) mnuInsert.MenuItems.Add(DataField.ColumnName, new EventHandler(InsertMenuItems_Click)); } private void InsertMenuItems_Click(object sender, System.EventArgs e) { TXTextControl.TextField textField = new TXTextControl.TextField(); textField.Text = "(" + ((MenuItem)sender).Text + ")"; textField.Name = ((MenuItem)sender).Text; textField.ShowActivated = true; textField.DoubledInputPosition = true; textControl1.TextFields.Add(textField); }
本文出自 “” 博客,请务必保留此出处