Products Technologies Demo Docs Blog Support Company

Removing TextFields in a Loop

Modifying a collection during a standard foreach loop causes runtime errors in .NET. This code snippet shows how to use the TextFieldCollection.TextFieldEnumerator in TX Text Control to safely iterate and remove TextField objects from a TextFieldCollection inside a counted for loop.

Removing TextFields in a Loop

A typical problem with collections is the fact that you can't remove elements of the collection in a loop.

To remove specific fields in TX Text Control, you could add the fields to another array in order to remove these fields using the TextFields.Remove method or you can use the field enumerator:

TXTextControl.TextFieldCollection.TextFieldEnumerator fieldEnum = textControl1.TextFields.GetEnumerator();
int fieldCounter = textControl1.TextFields.Count;

for (int i = 0; i <= fieldCounter; i++)
{
 fieldEnum.MoveNext();
 TXTextControl.TextField curField = (TXTextControl.TextField)fieldEnum.Current;
 textControl1.TextFields.Remove(curField);
}

This little code snippet removes all fields from the TextFieldCollection of TX Text Control. Of course, this could also be easily solved using the Clear method of the TextFieldCollection. It just should show how to use the enumerator.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

Related Posts

Windows FormsWPF.NET

Create a Table of Contents in Windows Forms using C#

This article explains how to create a table of contents in Windows Forms using the ribbon or programmatically. Creating a table of contents is required to organize large documents.


Windows FormsList.NET

Two Ways to Restart Numbered Lists in TX Text Control

In TX Text Control, numbered lists are continued by default and need to be reset when required. There is more than one way if you want to restart numbered lists in a document. In this article, two…


.NETSample

Paste Special: The Easy Way to Implement

TX Text Control version 15.0 introduced a ClipboardFormat parameter on the Paste method, enabling native Paste Special functionality. The GetClipboardFormats method returns all available clipboard…


.NETSampleSections

How to Remove All Section Breaks in a Document?

TX Text Control 15.0 adds per-section page column support alongside existing section breaks. To remove all section breaks programmatically, iterate through SectionCollection using…


.NETPrintingSample

Batch Printing: How to Print Documents in One Print Job

Batch printing multiple documents as a single print job using TX Text Control relies on a .NET PrintDocument with PrintPage and QueryPageSettings events. Each page is rendered individually via the…

Share on this blog post on: