Deleting Elements

Deleting Elements

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

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 element ids.
ICollection<Autodesk.Revit.DB.ElementId> idSelection = null ;
UIDocument uidoc = new UIDocument(document);
foreach (Autodesk.Revit.DB.Element elem in uidoc.Selection.Elements)
{
        Autodesk.Revit.DB.ElementId id = elem.Id;
        idSelection.Add(id);
}

ICollection<Autodesk.Revit.DB.ElementId> deletedIdSet = document.Delete(idSelection);

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.