How do you find the parent element of a part?
I'm building an exporter, and it can export parts just fine, but their name is always just "part". I want to modify their name to reflect the ElementId of the element they were created from. I cannot seem to find a way to work backwards from the part to its parent. PartUtils only seems to have methods for finding the parts belonging to a specific parent, not the parent beloning to a specific part...
Solved! Go to Solution.
Solved by preynoldsarch. Go to Solution.
Intersting, I did some snooping and couldn't find it. It seems the API has no way of retrieving this info from a part.. The only parameters there are is the name and type of the parent family. As A workaround you could loop through the wall types and find the wall with the same name as the Orignal Type parameter of the part ..
Yeah, I thought of that, but that is so time consuming, especially in a project with thousands of walls....
I think what I'm going to have to do is generate the parts before the export, hide the parts and show the wall, and whenever my exporter hits a wall, just ask it for its parts instead and export their data... It's not ideal, but if it's what I have to do so be it.
It really seems stupid for them to not have a way to access the parent object...
For those who are intereseted, I've found a way to do this thanks to The Building Coder.
foreach(Element element in ElementSet) { Part p = element as Part; ICollection<LinkElementId> lIds = p.GetSourceElementIds(); if (lIds.Count != 1) { //Error: It has more than one source element, it cannot be processed return Result.Failed; } LinkElementId lId = lIds.First<LinkElementId>(); ElementId parentId = lId.HostElementId; }
The foreach is pseudo-code, and it may be possible to handle the "More than one source element" error, but I don't need to for my purposes, so I didn't bother.
Basically, the first (and only) LinkElementId is the ElementId of the part's parent element.
Enjoy ^^
the above only works if your part has no divisions, if you have divisions in your part then the Host Element will be another part, so you need to check the source for each host until it is not a part, then that will return the non part Host.
private Element GetPartHost(Part part)
{
Part thisPart = part;
Element element = part;
string categoryName = "Parts";
while (categoryName.Equals("Parts"))
{
LinkElementId sourceId = thisPart.GetSourceElementIds().First();
Element hostSourceId = part.Document.GetElement(sourceId.HostElementId);
if (hostSourceId != null)
{
if(hostSourceId is Part)
{
thisPart = hostSourceId as Part;
}
else
{
element = hostSourceId;
categoryName = hostSourceId.Category.Name;
}
}
else
{
return null;
}
}
return element;
}