Search code examples
c#.netcheckboxms-officeoffice-interop

Checkbox disabled for Word document created using Microsoft.Office.Interop.Word


I am trying to create a Word document with checkboxes in it using Microsoft.Office.Interop.Word. I have used the following references to do so:

I have successfully generated a Word document with a checkbox but unfortunately it is disabled. What I am trying to achieve is to have a checkbox that can be checked/unchecked.

In the screenshot below, you can see that I have 3 checkboxes. The 1st one is generated using Microsoft.Office.Interop.Word and the 2nd and 3rd ones were created manually in Word 2016. The first one cannot be marked as checked/unchecked while the 2nd and 3rd ones behave just like a normal checkboxes

enter image description here

And this is the code I used to generate the Word document.

private void btnCreateWordInterop_Click(object sender, EventArgs e)
    {
        Word._Application word_app = new Word.ApplicationClass();
        word_app.Visible = true;

        object missing = Type.Missing;
        Word._Document word_doc = word_app.Documents.Add(ref missing, ref missing, ref missing, ref missing);
        Word.Paragraph para = word_doc.Paragraphs.Add(ref missing);
        para.Range.Text = "Chrysanthemum Curve";
        object style_name = "Heading 1";
        para.Range.set_Style(ref style_name);
        para.Range.InsertParagraphAfter();

        //Microsoft.Office.Interop.Word.Range range = 
        para.Range.Collapse(ref missing);
        Word.FormField checkBox = word_doc.FormFields.Add(para.Range, Word.WdFieldType.wdFieldFormCheckBox);
        para.Range.InsertAfter("  Checkbox generated by Microsoft.Office.Interop.Word");

        // Save the document.
        object filename = @"C:\Users\Username\Desktop\InteropWord.docx";

        word_doc.SaveAs(ref filename, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing,
            ref missing);

        //Close.
        object save_changes = false;
        word_doc.Close(ref save_changes, ref missing, ref missing);
        word_app.Quit(ref save_changes, ref missing, ref missing);

        MessageBox.Show("Saved");
    }

How can I make the generated checkbox enabled?


Solution

  • Instead of using FormFields I'd recommend using Content Controls for this. These are more 'User Friendly' and easier to work with in general.

    Change this line:

    Word.FormField checkBox = word_doc.FormFields.Add(para.Range, Word.WdFieldType.wdFieldFormCheckBox);
    

    Using a Content Control it would be something like (from the top of my head)

    Word.ContentControl checkbox = para.Range.ContentControls.Add(Word.WdContentControlType.wdContentControlCheckBox);