1

I'm deleting a feature from a shapefile with this code:

IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspaceFactory.openFromFile("C:/Users/me/Desktop", 0);
IFeatureClass featureClass = featureWorkspace.openFeatureClass("sondage");
IWorkspaceEdit wse=(IWorkspaceEdit)featureWorkspace;
IQueryFilter qf=new QueryFilter();
String s="SALB 01";
qf.setWhereClause("n_sondage='"+s+"'");
IFeatureCursor pFeatureCursor = featureClass.search(qf, false);                 
int id=pFeatureCursor.nextFeature().getOID();
wse.startEditing(false);
wse.startEditOperation();
IFeature feat=featureClass.getFeature(id);
feat.delete();
wse.stopEditOperation();
wse.stopEditing(true);

It works, but when I called this function in another class in the same project, the feature is not deleted and the shape couldn't be drawn any more.

2

Please use an update cursor and not a search cursor. You can replace the table/row by featureclass/feature from my example.

ICursor cur = table.Update(queryFilter, false);
if (cur != null)
{
    IRow row = cur.NextRow();
    if (row != null)
    {
        while (row != null)
        {
            row.Delete();
            row = cur.NextRow();
        }                             
    }
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(cur);

Note: Please keep in mind to handle when no features or multiple features are returned in the cursor.

  • Thank you very much, that works, i think the problem is that i wasn't using the releaseComObject. – Mouad Sep 12 '16 at 14:39
  • Why did you "ReleaseComObject"? – Chris Stayte Nov 9 '16 at 18:16
  • since you are using "while" loop "if (row != null)" is not necessary. Thanks for tje solution, though :) – shika-kun Feb 27 '19 at 15:28

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.