0

I am trying to delete all fields from a feature class except 4 Fields "FID", "Shape", "OBJECTID" and "SUBTYPECD"

With below code:

            IGPUtilities2 gpUtils = new GPUtilitiesClass();
            IFeatureClass featureClass = gpUtils.OpenFeatureClassFromString(@"FCpath\Land.shp");
            IFields2 fields = featureClass.Fields as IFields2;
            IField2 nameField = null;

            for (int fieldIndex = 0; fieldIndex < fields.FieldCount; fieldIndex = fieldIndex + 1)
            {

                nameField = fields.Field[fieldIndex] as IField2;

                if (nameField.Name != "FID" && nameField.Name != "Shape" && nameField.Name != "OBJECTID" && nameField.Name != "SUBTYPECD")
                {

                    featureClass.DeleteField(nameField);

                }

            }

it is working but doing a strange behavior, it only deletes half of total Field count

for example if there are 50 Fields it will delete only 25. could not understand why this is skipping fields in deleting.

1

I figured out the problem.

Every time one Field is deleted and fields.FieldCount will be changed and reduced by one, also fieldIndex will be increased by one, hence will delete alternate field.

I have corrected the loop :

            IGPUtilities2 gpUtils = new GPUtilitiesClass();
            IFeatureClass featureClass = gpUtils.OpenFeatureClassFromString(@"D:\Akhil\ToolBox\Test\Merge.shp");
            IFields2 fields = featureClass.Fields as IFields2;

            IField2 nameField = null;

            List<string> STR = new List<string>();

            for (int fieldIndex = fields.FieldCount - 1 ; fieldIndex > -1; fieldIndex = fieldIndex - 1)
            {                   
               nameField = fields.Field[fieldIndex] as IField2;
               if (nameField.Name != "FID" && nameField.Name != "Shape" && nameField.Name != "OBJECTID" && nameField.Name != "SUBTYPECD")
               {
                   featureClass.DeleteField(nameField);
               }
            }
  • Just food for thought, an alternative approach would be to call the Delete Field geo-processing tool using IGeoProcessor and you would feed in a list of fields you wanted removed. – Hornbydd Jun 21 '17 at 11:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.