How to access legacy forms checkboxes and ActiveX checkboxes in Word using C#!

https://msdnshared.blob.core.windows.net/media/2016/08/7827.NinjaAwardTinyBronze.pngBronze Award Winner


Hi! 

I am assuming you are using VSTO to try and access checkboxes in a Microsoft Word document using C# and automation.

The following code assume you are familiar with how to use VSTO and how to access a document in general. I am just going to show you how to access both legacy checkboxes and active checkboxes since you may not know which ones the user setup.

Apparently, doing this simple task is not well documented. None of my searches lead to anything useful, so here is what I wrote for how to handle the search for all checkboxes in a word document then set them all to false. Obviously, you can use this to get values, launch rockets, whatever it is you want to do.

[csharp]
//go through legacy fields.
foreach (FormField c in vstoDoc.FormFields)
{
try
{
if (c.Type == WdFieldType.wdFieldFormCheckBox)
{
if (c.CheckBox.Value)
c.CheckBox.Value = false;
}
}
catch { }
}

//go through the activex fields.
foreach(Field f in vstoDoc.Fields)
{
if (f.Type == WdFieldType.wdFieldOCX)
{
try
{
if (f.OLEFormat != null)
{
if(f.OLEFormat.ProgID.ToLowerInvariant().Contains("checkbox"))
{
if(f.OLEFormat.Object.Value)
f.OLEFormat.Object.Value = false;
}
}
}
catch { }
}
}

[/csharp]

I am sure you figured out my variable vstoDoc is the document. If not, well, McDonalds always need a new fry cook.

Happy Coding!