Instantiating Objects

Now that you have a Sentence class, you will create two instances of the class, assigning a different value to the Text property of each class. Finally, you'll retrieve the value of the Text property for each Sentence object and insert it into your document. Follow these steps:

1. In Solution Explorer, right-click ThisDocument.vb and select View Code.

2. The Code Editor opens, and two default event handlers are visible. The first is the Startup event handler, and the second is the Shutdown event handler for the document.

3. Add the code in Listing 3.3 to the Startup event handler of ThisDocument.

The code concatenates the text in Sentence1 and Sentence2 and then uses the InsertAfter method to insert the text into the first paragraph of the document. Because the code is added to the ThisDocument class, the Me keyword is used to represent the VSTO document (Microsoft.Office.Tools.Document, which wraps the native Document class).

Listing 3.3. Creating two Sentence objects

Dim Sentence1 As New Sentence() Dim Sentence2 As New Sentence() Sentence1.Text = "This is my first sentence. " Sentence2.Text = "This is my second sentence. " Me.Paragraphs(1).Range.InsertAfter( _ Sentence1.Text & Sentence2.Text)

4. Press F5 to run the solution.

When the solution runs and the Word document is created, the Startup event handler is raised and two instances of the Sentence class are created. The code then assigns a different string to each Sentence object. Finally, the value of each Sentence object is retrieved and inserted into the first paragraph of the document, as shown in Figure 3.1.

This is my first sentence. This is my second sentence.

Figure 3.1. Text inserted into the document using the Sentence class

5. Stop execution of the solution code by clicking Stop Debugging on the Debug menu, and then close the solution.

0 0

Post a comment