When you do not know at design time how many controls will be required in a document at run time, you can add controls dynamically in response to events.

This sample demonstrates how to add and remove Windows Forms controls and host controls at run time.

Security Note:

This sample code is intended to illustrate a concept, and it shows only the code that is relevant to that concept. It may not meet the security requirements for a specific environment, and it should not be used exactly as shown. We recommend that you add security and error-handling code to make your projects more secure and robust. Microsoft provides this sample code "AS IS" with no warranties.

For information about how to install the sample project on your computer, see How to: Install and Use Sample Files Found in Help.

To run this sample

  1. Press F5.

  2. Click inside the document.

  3. Select a check box in the task pane.

    A control is added at the cursor location.

  4. Clear the check box that you selected.

    The control is removed from the document.

Controls created by add-ins are not saved automatically in the document. This sample saves the control information to a custom XML part so that the controls can persist between Word instances.

To save the controls

  1. Press F5.

  2. Click inside the document.

  3. Select a check box in the task pane.

    A control is added at the cursor location.

  4. Click the Save button.

    The Delete controls dialog box appears.

  5. Click No.

  6. In the Save As dialog box, type a file name for this worksheet, and click Save.

  7. Exit Word.

  8. Open the file that you just saved.

    The controls are still present in your document.

Demonstrates