Replace all FieldFormCheckBox in document completely with text based on Checked

I would like to replace all FieldFormCheckBoxes in a document with the text [X] or [ ]. Tried a number of methods without success. The checkbox fields need to be removed.

Please advise.

@tylerjmiller

Please use the following code example to replace the checkbox with text. Hope this helps you.

Document document = new Document(MyDir + "in.docx");
DocumentBuilder builder = new DocumentBuilder(document);
NodeCollection formfields = document.GetChildNodes(NodeType.FormField, true);

foreach (FieldStart fieldStart in document.GetChildNodes(NodeType.FieldStart, true))
{

    if (fieldStart.GetField().Type == FieldType.FieldFormCheckBox)
    {
        builder.MoveToField(fieldStart.GetField(), true);
        builder.Write("[X]");
        fieldStart.GetField().Remove();
    }
}

document.Save(MyDir + @"19.10.docx");

@tylerjmiller,

In case you face any problems, please ZIP and attach the following resources here for further testing:

  • Your simplified input Word document containing the checkbox fields
  • Aspose.Words 19.11 generated output DOCX file showing the undesired behavior
  • Your expected DOCX Word document showing the correct output. You can create expected document by using MS Word.

As soon as you get these pieces of information ready, we will start further investigation into your scenario and provide you code to achieve the same output by using Aspose.Words. Thanks for your cooperation.

Hi, I have the same requirement, but I need to distinguish between checked/unchecked state in order to show [X] or [ ]. As far as I know, this state is not accessible in the Field object, only in the FormField.

How can I get the FormField from the Field? This code seems to work, but I don’t know how reliable it is:

FormField formField = field.End.PreviousSibling as FormField;
bool checked = formField.Checked;

Thank you

@DeliaZgz Form fields in MS Word document are wrapped with bookmark. So you can simply use this bookmark as a place where replacement should be inserted. For example see the following code:

Document doc = new Document(@"C:\Temp\in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
foreach (FormField ff in doc.Range.FormFields)
{
    if (ff.Type == FieldType.FieldFormCheckBox)
    {
        builder.MoveToBookmark(ff.Name, false, true);
        builder.Write(ff.Checked ? "[X]" : "[ ]");
    }
}
// Remove firm fields.
doc.Range.Fields.Where(f => f.Type == FieldType.FieldFormCheckBox).ToList()
    .ForEach(f => f.Remove());

doc.Save(@"C:\Temp\out.docx");
1 Like