Deleting Elements

The Revit Platform API provides Delete() methods to delete one or more elements in the project.

Deleting Elements

Table 23: Delete Members

Member

Description

Delete(ElementId)

Delete an element from the project using the element ID

Delete(ICollection<ElementId>)

Delete several elements from the project by their IDs.

The first method deletes a single element based on its Id, as shown in the example below.

Code Region: Deleting an element based on ElementId

private void DeleteElement(Autodesk.Revit.DB.Document document, Element element)
{
        // Delete an element via its id
        Autodesk.Revit.DB.ElementId elementId = element.Id;
        ICollection<Autodesk.Revit.DB.ElementId> deletedIdSet = document.Delete(elementId);

        if (0 == deletedIdSet.Count)
        {
                throw new Exception("Deleting the selected element in Revit failed.");
        }

        String prompt = "The selected element has been removed and ";
        prompt += deletedIdSet.Count - 1;
        prompt += " more dependent elements have also been removed.";

        // Give the user some information
        TaskDialog.Show("Revit", prompt);
}
Note: When an element is deleted, any child elements associated with that element are also deleted, as indicated in the sample above.

The API also provides a way to delete several elements.

Code Region: Deleting multiple elements based on Id

// Delete all the selected elements via the set of elements
UIDocument uidoc = new UIDocument(document); 
ICollection<ElementId> elements = uidoc.Selection.GetElementIds();
ICollection<Autodesk.Revit.DB.ElementId> deletedIdSet = document.Delete(elements);

if (0 == deletedIdSet.Count)
{
    throw new Exception("Deleting the selected elements in Revit failed.");
}

TaskDialog.Show("Revit","The selected element has been removed.");
Note: After you delete the elements, any references to the deleted elements become invalid and throw an exception if they are accessed.