Getting the best out of bookmarks in Microsoft Word

Suppose you have a .NET application that needs to open a Word document and insert data from a database or from an XML file. To provide this functionality, Microsoft Word documents contain bookmarks, a set of "placeholders" that allow you to insert text at design time and runtime. I want to share with you some guidelines that I use to work with bookmarks:

To go to a particular location and insert text, you can create your own bookmarks using the Boomark object. You can also take advantage of the set of prefedined bookmarks to go to a particular location in a document. For example, to insert text at the end of a document, you can do something like:

private object _endOfDoc = "\\endofdoc";
Word.Range _rng = doc.Bookmarks.get_Item(ref _endOfDoc).Range;
_rng.Text = "Bookmark demo";

There are times when you have a huge document and you get lost with all the bookmarks that you might have, or like me, you create some bookmarks and forget or mispell the names you defined for the bookmarks (doh!) while coding. You can use the following snippet of code to get a list of all the bookmarks that you have in your document:

public void ListBookmarks()
{
StringWriter sw = new StringWriter();

foreach (Word.Bookmark bookmark in Word.Application.ActiveDocument.Bookmarks)
{
sw.WriteLine("Name: {0}, Contents: {1}", bookmark.Name, bookmark.Range.Text);
    }
MessageBox.Show(sw.ToString(), "Bookmarks and Contents");
}

You should also explore the "Bookmark View Controls" provided by Visual Studio Tools for Office v2.0. Take a look at this cool video created by Paul Stub and learn more about bookmarks.

Happy bookmark programming!