omar wasfi
omar wasfi

Reputation: 567

How to know if Word.docx Check Box (checkboxsymboltype in c# ) is checked or not?

I have a word document (document.docx) that have more than checkbox.

enter image description here

I want to know which one is check.

I can get all the checkboxes in the document by using

using DocumentFormat.OpenXml.Wordprocessing;

WordprocessingDocument documentFormA = WordprocessingDocument.Open(formALocation, true);

var checkBoxs = documentFormA.MainDocumentPart.Document.Body.Descendants<CheckBoxSymbolType>();

But this is the results that I get enter image description here

I can't differentiate which one is selected and which one is not at all.

Upvotes: 0

Views: 722

Answers (2)

Bruno Ferreira
Bruno Ferreira

Reputation: 484

I managed to solve the same issue with:

foreach (var checkBox in document.Descendants<CheckBox>()) {
    Checked state = checkBox.GetFirstChild<Checked>();
    if(state.Val.Value == true) {
    //checked
    }
}

Upvotes: 0

Kaspar Kjeldsen
Kaspar Kjeldsen

Reputation: 992

I've created a blank document and inserted 2 checkboxes in it from the developer tab. I then checked the first box and closed the document.

Image of 2 checkboxes

I am able to extract the value of the checkboxes like this:

using (var wordDoc = WordprocessingDocument.Open(@"C:\test\checkbox.docx", true))
{
    MainDocumentPart mainPart = wordDoc.MainDocumentPart;
    var document = mainPart.Document;
    
    var checkboxes = document.Body.Descendants<SdtContentCheckBox>();
    foreach (var checkbox in checkboxes)
    {
        Console.WriteLine(checkbox.Checked.Val);
    }
}

Which will output:

1

0

Hope this helps.

Note that SdtContentCheckbox is in DocumentFormat.OpenXml.Office2010.Word and not DocumentFormat.OpenXml.Wordprocessing

Upvotes: 1

Related Questions