Search code examples
c#docxform-fieldsgembox-document

Edit form controls with GemBox.Document


How can we write or modify existing values of form controls in Word documents using GemBox.Document?
I found the examples for creating and reading, but I just cannot find one for writing...

I tried using this:

// Input file from 'reading' example.
DocumentModel document = DocumentModel.Load("FormFilled.docx");
FormFieldDataCollection formData = document.Content.FormFieldsData;

FormFieldData fullNameData = formData.First(ffd => ffd.Name == "FullName");

// I cannot do this, FormFieldData.Value is read only!
fullNameData.Value = "My Name";

But FormFieldData.Value has only get, so is this possible or not?


Solution

  • Yes this is possible, try this:

    DocumentModel document = DocumentModel.Load("FormFilled.docx");
    // Get a snapshot of all form fields in the document.
    FormFieldDataCollection formData = document.Content.FormFieldsData;
    
    // Edit "FullName" text box field.
    FormTextData fullNameData = (FormTextData)formData["FullName"];
    fullNameData.Field.ResultInlines.Content.LoadText("Jane Doe");
    
    // Edit "BirthDate" text box field.
    FormTextData birthDateData = (FormTextData)formData["BirthDate"];
    birthDateData.Field.ResultInlines.Content.LoadText(
        new DateTime(2000, 1, 1).ToString(birthDateData.ValueFormat));
    
    // Edit "Salary" text box field.
    FormTextData salaryData = (FormTextData)formData["Salary"];
    salaryData.Field.ResultInlines.Content.LoadText(
        5432.1.ToString(salaryData.ValueFormat));
    
    // Uncheck "Married" check box field.
    FormCheckBoxData marriedData = (FormCheckBoxData)formData["Married"];
    marriedData.Value = false;
    
    // Select "Female" from drop down field, note that "genderData.Items
    // contains a list of drop down field's items that you can select.
    FormDropDownData genderData = (FormDropDownData)formData["Gender"];
    genderData.SelectedItemIndex = 2;
    
    document.Save("FormFilledOutput.docx");
    

    I hope this helps.

    UPDATE:

    In one of a newer GemBox.Document's bug fix versions the FormTextData.Value property has both getter and setter, so the above can be simplified with the following:

    // Edit "FullName" text box field.
    FormTextData fullNameData = (FormTextData)formData["FullName"];
    fullNameData.Value = "Jane Doe";
    
    // Edit "BirthDate" text box field.
    FormTextData birthDateData = (FormTextData)formData["BirthDate"];
    birthDateData.Value = new DateTime(2000, 1, 1);
    
    // Edit "Salary" text box field.
    FormTextData salaryData = (FormTextData)formData["Salary"];
    salaryData.Value = 5432.1;
    

    Also you can refer to this example.