I've tried to write a command in C# to list all sheets on which the currently selected legend is placed. However, I can't get it to work in any way. It makes me doubt if it's possible at all in revit to list sheets on which views are placed (given that there is no way to create a schedule of views)?
code:
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System.Collections.Generic;
using System.Linq;
[Transaction(TransactionMode.Manual)]
public class ListLegendSheetsCommand : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
// Get the active Revit document
UIDocument uidoc = commandData.Application.ActiveUIDocument;
Document doc = uidoc.Document;
// Get the currently selected element (legend)
var selectedIds = uidoc.Selection.GetElementIds();
if (selectedIds.Count != 1)
{
TaskDialog.Show("Error", "Please select one legend.");
return Result.Failed;
}
Element selectedElement = doc.GetElement(selectedIds.First());
// Get all Viewports and find where the selected legend is placed
FilteredElementCollector viewportCollector = new FilteredElementCollector(doc)
.OfClass(typeof(Viewport));
List<ViewSheet> sheetsWithLegend = new List<ViewSheet>();
List<Dictionary<string, object>> sheetEntries = new List<Dictionary<string, object>>();
foreach (Viewport viewport in viewportCollector.Cast<Viewport>())
{
if (viewport.ViewId == selectedElement.Id)
{
// Get the ViewSheet where this viewport is located
ViewSheet sheet = doc.GetElement(viewport.SheetId) as ViewSheet;
if (sheet != null)
{
sheetsWithLegend.Add(sheet);
// Prepare the data for the DataGrid
Dictionary<string, object> entry = new Dictionary<string, object>
{
{ "Sheet Name", sheet.Name },
{ "Sheet Number", sheet.SheetNumber },
{ "Id", sheet.Id.IntegerValue }
};
sheetEntries.Add(entry);
}
}
}
if (sheetsWithLegend.Count == 0)
{
TaskDialog.Show("No Sheets", "The selected legend is not placed on any sheets.");
return Result.Succeeded;
}
// Prepare the properties to display in the DataGrid
List<string> propertyNames = new List<string> { "Sheet Name", "Sheet Number" };
// Use the provided CustomGUIs.DataGrid method to display the list and allow the user to select a sheet
var selectedSheetEntries = CustomGUIs.DataGrid(sheetEntries, propertyNames, false);
if (selectedSheetEntries == null || selectedSheetEntries.Count == 0)
{
TaskDialog.Show("Error", "No sheet selected.");
return Result.Cancelled;
}
// Get the selected sheet's ID
int selectedSheetId = (int)selectedSheetEntries.First()["Id"];
ElementId selectedSheetElementId = new ElementId(selectedSheetId);
// Open the selected sheet
ViewSheet selectedSheet = doc.GetElement(selectedSheetElementId) as ViewSheet;
if (selectedSheet != null)
{
uidoc.ActiveView = selectedSheet;
}
else
{
TaskDialog.Show("Error", "Failed to open the selected sheet.");
return Result.Failed;
}
return Result.Succeeded;
}
}