index > Visual Studio Tools for Office > MailMerge.CreateDataSource

MailMerge.CreateDataSource


Is there anyway to get a Dataset or a DataTable as the source? The header in any case would be > 255 characters.

Is there another way to have <<variable>> fields populated without using MailMerge?

TIA




One if by Land, Two if by Sea
zedekiah
You could iterate through the merge fields programmatically, replace those fields with the correct data item from your data source. This would allow you to use, say, ADO .Net and DataSets/DataTables in your code ....

Here is some sample code (originally provided by Cindy M) that outlines how to iterate through the merge fields contained in a document (since there is no "Merge Field" collection):

Word.Section sec = this.Sections[1];
Word.Range rng = sec.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range
foreach (Word.Field fld in rng.Fields)
}
if (fld.Type == Microsoft.Office.Interop.Word.WdFieldType.wdFieldMergeField)
{
string dataFieldName = fld.Code.Text.Trim();
}
}
Douglas H. Troy

Thanks, I got the datasource and the mergefields to connect. The problem is now, how do I update the MergeField with the data in the datatable?

foreach (Word.Field fld in rng.Fields)
{
if (fld.Type == Microsoft.Office.Interop.Word.WdFieldType.wdFieldMergeField)
{
foreach(DataColumn col in this.MyExpenses.Tables[0].Columns)
{
if (fld.Code.Text.IndexOf(col.ToString()) > -1)
{
fld.Code.Text = MyExpenses.Tables[0].Rows[0][col].ToString();
break;
}
}
}




One if by Land, Two if by Sea
zedekiah

Hi zedekiah

First, I need to reduce your expectations a bit: Word does not provide a way to link a dataset, data source, data table or anything else "in memory" to a document as a mail merge data source. Word requires the data source to be made available as a file, in a "traditional" location (no URLs allowed), in a "flat table" format.

The best you can do if you don't want to create a file is "cheat". The code Doug gave you "cheats": it locates the merge fields, lets you match them field name to your data table. BUT, then you must put the data in... in place of the merge field. What you appear to be doing (as best I can tell) is putting the value into the field's code. This won't work. You have to actually remove the field and put your text in its place. No guarantees on what I'm about to show you, because I'm typing this from the top of my head, but it should give you an idea how to approach the problem:

Word.Range rng = fld.Result;
fld.Delete(missing);
rng.Text = MyExpenses.Tables[0].Rows[0][col].ToString();




-- Cindy Meister (Word MVP)
Cindy Meister

Yes, that works, thanks a lot. I try to access the data island in the word document and it fails to find the cached data item.

statements 1 and 2 always return false and statement 3 "Object reference not set to an instance of an object"

I did open and save the document before trying any of this.

VSTO WORD Code:

[Cached()]
public Expenses MyExpenses = new Expenses();

private void ThisDocument_Startup(object sender, System.EventArgs e)
{
if (this.NeedsFill("MyExpenses"))
{

this.EmpId = 513;
using (OleDbConnection cn = new OleDbConnection(ConnectionString))
{
string QueryName = "TERMTOOL_MAILMERGE_Get_List";
cn.Open();

using (OleDbCommand cm = new OleDbCommand(QueryName, cn))
{

cm.CommandType = CommandType.StoredProcedure;
OleDbParameter parameterItemId = new OleDbParameter("@EE__", OleDbType.Integer, 4);
parameterItemId.Value = EmpId;
cm.Parameters.Add(parameterItemId);

OleDbDataAdapter objAdap = new OleDbDataAdapter(cm);

objAdap.SelectCommand = cm;

objAdap.Fill(this.MyExpenses, "Expenses");
}
}
}

Word.Section sec = this.Sections[1];
Word.Range rng = this.Sections[1].Range;
// Word.Range rng = sec.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
foreach (Word.Field fld in rng.Fields)
{
if (fld.Type == Microsoft.Office.Interop.Word.WdFieldType.wdFieldMergeField)
{
foreach(DataColumn col in this.MyExpenses.Tables[0].Columns)
{
if (fld.Code.Text.IndexOf(col.ToString()) > -1)
{
Word.Range range = fld.Result;
fld.Delete();
range.Text = MyExpenses.Tables[0].Rows[0][col].ToString();
break;
}
}
}

ASPX.PAGE CODE:

string filename = @"C:\TeamProjects\TermTool\TermTool\TermTool\CheckOutForms.doc";


FileStream file = new FileStream(filename,FileMode.Open, FileAccess.Read);
byte[] template;
try {
template = new byte[file.Length];
file.Read(template, 0, (int)file.Length);
}
finally {
file.Close();
}

/*1- */ bool IsCacheEnabled = ServerDocument.IsCacheEnabled(filename);

/* 2- */ bool IsCustomized = ServerDocument.IsCustomized(filename);

ServerDocument sd = new ServerDocument(template, ".DOC");

try {
/*3*/ sd.CachedData.HostItems["TermTool.ThisDocument"].CachedData["MyExpenses"].SerializeDataInstance(MyExpenses);
sd.Save();

// "template" still has the original bytes. Get the new bytes.
// template = sd.Document;
}
finally {
sd.Close();
}
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/vnd.ms-word";
Response.OutputStream.Write(template, 0, template.Length);
Response.Flush();
Response.Close();
}




One if by Land, Two if by Sea
zedekiah

That was not the problem. Come to find out I had not published. There is another problem. We are instructed to first save the document before we attempt to change the data island. As I understand it, the code I got from Cindy eliminates the mail merge fields so I cannot change the anyway. Is there any work around so I can change data islands and send to different people using Mail Merge Fields?




One if by Land, Two if by Sea
zedekiah

Hi zedekiah

I really think you're misunderstanding how Word and data islands and such work...

VSTO + data islands + Word are set up to use BOOKMARK objects as targets. Not merge fields. If you're going to use VSTO, you should set up the "template" to use bookmarks controls, not merge fields. Then you can even use the ServerDocument functionality to populate the data, remove the VSTO customization and send the document - all without needing to automate Word at all. Here's one link on the topic

http://msdn2.microsoft.com/en-us/library/4c0hby0e.aspx




-- Cindy Meister (Word MVP)
Cindy Meister
reply 7

You can use google to search for other answers

 

More Articles

Action Pane Disappear
Excel Add-In showing up twice
Using user properties in Find method
Variable to store a range of a document
Big Trouble with Encrypted Emails in VSTO 2005
Getting the ExecutingAssembly Location / SecurityException
Increase performance of ControlCollection AddControl in Word
Upgrading excel workbook solution from VSTO v2 to VSTO v3
VSTO update database
how to create shims for add-ins created with VSTO if no VS2003?
Welcome to Bokebb   New Update   Joins the collection  
 

New Articles

Word OCX Control
deleting VSTO Word File from Bin while V…
Integration in an existing project
Problem with TaskPane initialization - p…
How to cancel a delete of a folder ?
Outlook addin AutoUpdate
Do I have VSTO?
Catching Unhandled Exceptions
Smart Tag - Method get_VerbCaptionFromID…
VSTO excel update question
drag drop into document object
Odd behavior on explicitly calling a cus…
Access Database Synchronizing
taskpane
Excel Interop from VS2005

Hot Articles

Missing InfoPath Template Project within…
How to embed remote attachments into an …
Get serious trouble in Powerpoint automa…
Outlook integration using redemption - c…
VSTO install balks at VS 2005 beta
Inspectors doing there own thing?
where can i find vsto apis for word proj…
Shared AddIn Deployment problem
Rapping button bar items...
Excel ListObject
Application level addin
Upgrade "path" for end-users w…
Trouble saving combo box values back an …
"Reload" listobject after UnLi…
BeforeDelete event of XMLNode in Word, D…

Recommend Articles

Standard User Analyser fails to start Ou…
Excel application type problem
B2TR and VSTO v3?
VSTO 2005- Word : Intercepting hyperlink…
VSTO 2005 - Problem loading excel file f…
Outlook MessageBox hidden when using Wor…
VSTO project does not appear in "VS…
ItemAdd Event Destination folder.
Outlook 2003?
Save a new File with a VSTO Solution
Displaying an icon on a commandbarbutton…
Problem while try to close Excel File Fr…
Remove This Smart Tag
Outlook : GAL
regarding actions pane