English

How To: Delete selected features using ArcObjects

Summary

Instructions provide a code sample which deletes selected features.

Procedure

  1. Start ArcMap.
  2. Open the Visual Basic Editor.

    In ArcMap, select Tools > Macros > Visual Basic Editor.

  3. In the Project Explorer window, expand Project.mxt and select ArcMap Objects > ThisDocument then right-click and select View Code.
    [O-Image] Visual Basic Project  Explorer
    Note:
    Code in the Project's ThisDocument code module will only run in the current map document. If you want to store the code in all your map documents open the Normal.mxt ThisDocument code module instead.

  4. Copy the following code into the code module.

    Code:
    Option Explicit

    Public Sub Main()

    Dim pDoc As IMxDocument
    Dim pLayer As IFeatureLayer
    Dim mySet As ISet
    Dim pFeature As IFeature
    Dim pEnumFeature As IEnumFeature
    Dim pEditor As IEditor
    Dim pUID As New UID

    Set pDoc = Application.Document
    Set pEnumFeature = pDoc.ActiveView.Selection
    pEnumFeature.Reset
    Set pFeature = pEnumFeature.Next
    pUID = "esricore.editor"
    Set pEditor = Application.FindExtensionByCLSID(pUID)

    Set pDoc = Application.Document

    'Make certain the layer is selected in the TOC
    Set pLayer = pDoc.SelectedLayer

    'Check to make certain that there is an edit session started
    If pEditor.EditState = esriStateNotEditing Then
    MsgBox "Cannot Edit outside of an edit session"
    End If
    'Call the DeleteSelectedFeatures sub procedure
    'and pass in the EnumFeature object.

    DeleteSelectedFeatures pEnumFeature
    pDoc.ActiveView.Refresh



    End Sub

    Private Sub DeleteSelectedFeatures(pEnumFeature As IEnumFeature)

    Dim pFeature As IFeature
    Dim mySet As esriCore.ISet
    Set mySet = New esriCore.Set
    Dim pFeatureEdit As IFeatureEdit

    pEnumFeature.Reset
    Set pFeature = pEnumFeature.Next

    'Takes features and writes them out to an ISet object
    Do Until pFeature Is Nothing
    Set pFeatureEdit = pFeature
    mySet.Add pFeature
    Set pFeature = pEnumFeature.Next
    Loop

    'Calls the deleteset method from IFeatureEdit
    'to delete the selected set of records
    pFeatureEdit.DeleteSet mySet

    End Sub


  5. Close the Visual Basic Editor.
  6. Add a feature class to ArcMap and select some features to delete.
  7. Select the layer in the table of contents and run the code.

    A. Click Tools > Macros > Macros to display the Macros dialog box.
    B. Select a macro and click Run.