Thursday, September 6, 2007

Adding content to Word "content control" programmatically

Category: Word programming
Level: Advance
Here is a small tip on how to add data to Word content control programmatically. If you don't know what are content controls, you can read about them at the following sites:
 http://blogs.msdn.com/microsoft_office_word/archive/2006/10/23/control-yourself.aspx
http://blogs.msdn.com/modonovan/archive/2006/05/23/604704.aspx
http://blogs.msdn.com/erikaehrli/archive/2006/08/11/word2007DataDocumentGenerationPart1.aspx
http://msdn2.microsoft.com/en-us/library/ms406053.aspx
The articles above will give you a clear picture about content controls. The beauty of content controls is that these can be populated with data programmatically. Of course, this could be done in different ways. Following is one way of doing it:

object contentcontrolIndex;
               
contentcontrolIndex = 1; //index of content controls always start from 1, not from 0!!
               
Word.ContentControl contentcontrolSample = this.Application.ActiveDocument.ContentControls.get_Item(ref contentcontrolIndex);

contentcontrolSample.Range.InsertAfter("This is a test!"); 

"this" in third line points to the current open document. When trying this code, replace "this.Application" with your own Word reference. If you want to learn more about this topic, read the following article (VSTO 2005 SE Sample):
http://www.microsoft.com/downloads/details.aspx?familyid=9331eaa4-fc4f-49e1-ac78-aa2f112d854e&displaylang=en
The code above assumes there is only one content control in the application. The index of the control will be 1. Using this technique, you can populate content controls with data retrieved from different data sources including databases and other documents.

-SSA

No comments:

Post a Comment