Adding Controls at Run Time

Most host controls can be added to the Word document at run time. There are two exceptions to this rule, both of them related to XML mapping. VSTO does not provide a way to add XMLNode and XMLNodes controls to the document programmatically. You can add these controls only when you map an XML element to the document using Word's native functionality at design time.

In Chapter 3, you learned that to create an instance of an object you must use the New keyword. This technique is not supported for pro-grammatically creating instances of view controls. Instead, VSTO provides a number of helper methods that enable you to add the controls to the document at run time. These methods are part of the Controls collection, and, in the case of Word, there is only one method available: AddBookmark. The AddBookmark method takes two parameters: the range where you want to add the bookmark, and the name you want to give the bookmark.

The code in Listing 6.8 shows how to add a bookmark to a range of text at run time and then apply bold formatting to the text in the bookmark.

Listing 6.8. Programmatically adding a bookmark to a range

Dim myBookmark As Microsoft.Office.Tools.Word.Bookmark = _ Me.Controls.AddBookmark(Me.Paragraphs(1).Range, _ "myBookmark") myBookmark.Font.Bold = True

When you pass the AddBookmark method a name to give the bookmark, you must make sure that the name is unique. Unlike VBA, where you can programmatically add a bookmark and give it the same name as an existing bookmark (thus moving the bookmark to a new location), you must supply unique names for VSTO bookmarks. If you supply a name that is already in use in the document, you will receive a ControlNameAlreadyExistsException, as shown in Figure 6.8.

Figure 6.8. Exception thrown when the bookmark name already exists in the document

To avoid this error, you should first check to make sure that a like-named bookmark doesn't already exist on the document. You can do that within the Controls collection of the document by using the Contains method, as the code in Listing 6.9 demonstrates.

Listing 6.9. Checking whether a bookmark already exists before adding it to a range

Dim bookmarkName As String = "EventTable"

If Not Me.Controls.Contains(BookmarkName) Then

Dim myBookmark As Microsoft.Office.Tools.Word.Bookmark = _ Me.Controls.AddBookmark(Me.Paragraphs(1).Range, _ bookmarkName) myBookmark.Font.Bold = True

End If

0 0

Post a comment