Walkthrough: Retrieve Selected Elements

Walkthrough: Retrieve Selected Elements

This section introduces you to an add-in application that gets selected elements from Revit.

In add-in applications, you can perform a specific operation on a specific element. For example, you can get or change an element's parameter value. Complete the following steps to get a parameter value:

  1. Create a new project and add the references as summarized in the previous walkthroughs.
  2. Use the UIApplication.ActiveUIDocument.Selection.Elements property to retrieve the selected object.

The selected object is a Revit SelElementSet. Use the IEnumerator interface or foreach loop to search the ElementSet.

The following code is an example of how to retrieve selected elements.

Code Region 2-7: Retrieving selected elements

[Autodesk.Revit.Attributes.Transaction(TransactionMode.ReadOnly)]    
public class Document_Selection : IExternalCommand
{
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
                ref string message, ElementSet elements)
        {
                try
                {
                        // Select some elements in Revit before invoking this command
                        
                        // Get the handle of current document.
                        UIDocument uidoc = commandData.Application.ActiveUIDocument;
                        // Get the element selection of current document.
                        Selection selection = uidoc.Selection;
                        ElementSet collection = selection.Elements;
 
                        if (0 == collection.Size)
                        {
                                // If no elements selected.
                                TaskDialog.Show("Revit","You haven't selected any elements.");
                        }
                        else
                        {
                                String info = "Ids of selected elements in the document are: ";
                                foreach (Element elem in collection)
                                {
                                        info += "\n\t" + elem.Id.IntegerValue;
                                }
                                
                                TaskDialog.Show("Revit",info);
                }
                }
                catch (Exception e)
                {
                        message = e.Message;
                        return Autodesk.Revit.UI.Result.Failed;
                }
                
                return Autodesk.Revit.UI.Result.Succeeded;
        }     
}

After you get the selected elements, you can get the properties or parameters for the elements. For more information, see Parameters.