Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files. Get free and professional technical support for Spire.Doc for .NET, Java, Android, C++, Python.

Wed Nov 14, 2018 6:02 pm

Can you tell me how I can get the index for a specific FormField in a Word document? I am using a foreach to loop over the form fields like this:

foreach (FormField field in doc.Sections[0].Body.FormFields)
{
//Get field name and value.
How can I get the index for each field in the FormFields collection?
}


Thank you,
Matt

shipman1225
 
Posts: 2
Joined: Wed Oct 17, 2018 3:26 pm

Thu Nov 15, 2018 7:04 am

Hi Matt,

Thanks for your inquiry.
If you just want to get the index of a field in the FormFields collection, you can simply use the for loop to get the field and then output the index. Please refer to the code below.
Code: Select all
 for (int i = 0; i < doc.Sections[0].Body.FormFields.Count; i++)
 {
     FormField field = doc.Sections[0].Body.FormFields[i];
     //Get field name and value.
     //How can I get the index for each field in the FormFields collection?
     //eg,find the field which named "email".
     if (!String.IsNullOrEmpty(field.Name) && "email".Equals(field.Name))
     {
         //get the index
         int index = i;
     }
 }

If it is not what you want, please describe your needs in detail and provide your sample Word file.
Sincerely,
Mike
E-iceblue support team
User avatar

Mike.Zhang
 
Posts: 93
Joined: Thu Sep 27, 2018 7:11 am

Thu Nov 15, 2018 1:18 pm

Hi Mike. Thanks for your reply. That is what I ended up doing but I'm getting different index values than when I was using the Microsoft Word Interop. The code I used for Word Interop was like this:

foreach (Microsoft.Office.Interop.Word.FormField field in doc.FormFields)
{
fieldIndex = field.Range.Fields[1].Index;
}


I have found that there are times when the code above returned a different index value than the code that you suggested. I would like to be able to understand why they are different. Please let me know if you have any information about this.

Thank you,
Matt

shipman1225
 
Posts: 2
Joined: Wed Oct 17, 2018 3:26 pm

Fri Nov 16, 2018 3:34 am

Hi,

Thanks for your feedback.
We are not so familiar with Microsoft Word Interop, so we don't know how they sort the fields internally. Different products might have different structure.
Any question about our products, feel free to contact us.
Sincerely,
Mike
E-iceblue support team
User avatar

Mike.Zhang
 
Posts: 93
Joined: Thu Sep 27, 2018 7:11 am

Return to Spire.Doc