Search code examples
c#ms-wordoffice-interop

How to check a box using Microsoft Word Interop Bookmarks C#


I am trying to modify a document with form fields and check boxes using C#'s Microsoft Word Interop. I've successfully managed to update the form fields using the following code, but I can't figure out how to mark a checkbox as "checked"

I created a list of items in the form that need to be updated, each form item has a BookmarkTag and respective data string:

string filename = @"C:\Users\...docx"; //removed for brevity

Application wordApp = null;
wordApp = new Application();
wordApp.Visible = false;
Document wordDoc = wordApp.Documents.Add(filename);

List<FormItem> formItems = new List<FormItem>
    {
        new FormItem { BookmarkTag = "author", Data = doc.Author.DisplayName },
        new FormItem { BookmarkTag = "phonenumber", Data = doc.Author.PhoneNumber },
    };

foreach(var formItem in formItems)
{
    if (!String.IsNullOrWhiteSpace(formItem.Data))
    {
        Bookmark bookmark = wordDoc.Bookmarks[formItem.BookmarkTag];
        bookmark.Select();
        wordApp.Selection.TypeText(formItem.Data);
    }
}

Obviously this will only work with text items, but how can I identify a bookmark like "checkbox1" and mark it's value as "checked"?

Thanks for the help!


Solution

  • When working with form fields it's better to address the formfield object rather than the bookmark name. The bookmark name serves as the index value for the FormFields collection.

    For example:

    object bookmark1 = "bkm1";
    object bookmark2 = "bkm2";
    wordDoc.FormFields[ref bookmark1].Result = "Text in textbox";
    wordDoc.FormFields[ref bookmark2].CheckBox.Value = true;