Trying to copy paste a Revit element using elementID
I am trying to copy a specific element beside another element the user selects. My code is saying that its copied, but I cannot see the new element in Revit. Please help!
using System;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using Autodesk.Revit.DB.Structure;
namespace RevitCommands
{
[Transaction(TransactionMode.Manual)]
public class AddAccessControlReader : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
// Get the Revit application and document
UIApplication uiApp = commandData.Application;
UIDocument uiDoc = uiApp.ActiveUIDocument;
Document doc = uiDoc.Document;
// Start a new transaction
using (Transaction transaction = new Transaction(doc, "Add Access Control Reader"))
{
try
{
// Start the transaction
transaction.Start();
// Select an element using the Revit UI selection mechanism
Reference elementRef = uiDoc.Selection.PickObject(ObjectType.Element, "Select an element");
Element selectedElement = doc.GetElement(elementRef);
// Check if the selected element is valid
if (selectedElement == null)
{
TaskDialog.Show("Error", "No element selected or element not found.");
transaction.RollBack();
return Result.Failed;
}
// Find the family instance to be copied
ElementId sourceElementId = new ElementId(1250743);
FamilyInstance sourceInstance = doc.GetElement(sourceElementId) as FamilyInstance;
if (sourceInstance == null)
{
TaskDialog.Show("Error", "Source element not found.");
transaction.RollBack();
return Result.Failed;
}
// Get the location of the selected element
LocationPoint elementLocation = selectedElement.Location as LocationPoint;
if (elementLocation == null)
{
TaskDialog.Show("Error", "Selected element does not have a valid location.");
transaction.RollBack();
return Result.Failed;
}
XYZ elementPosition = elementLocation.Point;
// Create a copy of the source instance at an offset position
XYZ instancePosition = elementPosition + new XYZ(0.1, 0, 0);
// Find a suitable level for placing the copied instance
Level targetLevel = doc.GetElement(selectedElement.LevelId) as Level;
FamilyInstance copyInstance = doc.Create.NewFamilyInstance(instancePosition, sourceInstance.Symbol, targetLevel, StructuralType.NonStructural);
if (copyInstance != null)
{
// Commit the transaction
transaction.Commit();
TaskDialog.Show("Success", "Element copy added successfully.");
return Result.Succeeded;
}
else
{
TaskDialog.Show("Error", "Failed to copy the element.");
transaction.RollBack();
return Result.Failed;
}
}
catch (Exception ex)
{
// Rollback the transaction
transaction.RollBack();
TaskDialog.Show("Error", "An error occurred: " + ex.Message);
return Result.Failed;
}
}
}
}
}