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.GetElementIds() method to retrieve the selected elements.
  3. Create a .addin file as explained in previous walkthroughs.

GetElementIds() returns a collection of ElementIds of the selected elements. It can be iterated with a foreach loop. Use the Document.GetElement() method to get the Element object for each ElementId in the selection.

The following code is an example of how to retrieve the ids of the selected element.

Code Region 2-7: Retrieving selected elements

using System;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI.Selection;
using Autodesk.Revit.UI;
using Autodesk.Revit.Attributes;
using System.Collections.Generic;

namespace Revit_Snippets
{
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.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;
                ICollection<ElementId> selectedIds = uidoc.Selection.GetElementIds();

                if (0 == selectedIds.Count)
                {
                    // 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 (ElementId id in selectedIds)
                    {
                       info += "\n\t" + id.IntegerValue;
                    }

                    TaskDialog.Show("Revit",info);
                }
            }
            catch (Exception e)
            {
                message = e.Message;
                return Autodesk.Revit.UI.Result.Failed;
            }

            return Autodesk.Revit.UI.Result.Succeeded;
        }
        /// </ExampleMethod>
    }
}

    

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