Search code examples
c#winformsms-wordoffice-interop

Fill a word document with inputs taken from Windows Form Application


I need to fill an Bank Account Form Word Document, from inputs taken from an Windows Form Application. I've searched the web about it, and found about Microsoft.Office.Interop.Word that can be used to edit a Word Document. However I'm not sure how I can put textboxes in the doc and put the information.

I'm attaching a picture of the form. Please give me any suggestions/help about it.

enter image description here


Solution

  • There are various approaches. Which to use depends to a certain extent on what kind of additional editing the user may want / need / is allowed to perform before the document is saved / printed. Here's a list of possibilities that come to mind:

    1. Form fields (when the document should be protected against changes)
    2. Content controls (can also be protected, but also allow formatted input)
    3. Bookmarks (simplest for the "interop")
    4. "Find/Replace" (Russel's suggestion - not my personal preference)
    5. Mail merge (although less with input directly into a Form)

    If there should be no user interaction you should also look at generating the file using the Open XML file format, especially if a server environment is involved.

    Follow-up from Comments: Content controls are accessed using the Document.SelectContentControlsByTitle and/or .SelectContentControlsByTag methods. These return an array of content controls with the specified Title / Tag property passed as an argument. Unlike bookmarks, multiple content controls can have the same title/tag. (This is why I say bookmarks are "simpler".)

    Content Controls also have an ID property (long-ish number) that can be passed as a string as the Index parameter for the ContentControls collection. The ID is assigned by Word when the Content control is inserted into the document and is read-only. Assuming you'd create the document and thus could know the ID values for each content control, you could use this instead of the above methods. contentControl = Document.ContentControls("2087486648")