A Practical Guide to SharePoint 2013

A Practical Guide to SharePoint 2013
A Practical Guide to SharePoint 2013 - Book by Saifullah Shafiq

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:
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):
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.

No comments:

Post a Comment