Getting an element from a string ID

The Revit API has two similar seeming versions of GetElement

  • Document.GetElement Method (String)
  • Document.GetElement Method (ElementId)

To use the string version, you must have a Element.UniqueId. This is not the same as the ElementID. The UniqueID is a hexadecimal GUID such as 4f2cb6f4-bd46-4877-8bd9-3dae7acfdfae-0002d7f3. Its usefulness is that it is stable across upgrades and workset operations such as Save To Central, while the ElementId property may change.

But what if you have an element ID stored as a string? Perhaps you read the ID as a string from a text file or the user entered the ID value in a text box of your user interface. As a human you would look at the number and see an integer. But if it is stored as a string in your code, then the computer will see a string and if you try to use it with GetElement then it will expect it to be a UniqueID GUID. You can’t use an element ID value as a string in Document.GetElement Method (String).

In this case, you will need to convert the id value from a string to an integer, use ElementId Constructor (Int32), and then use this element ID with GetElement. Here’s a bit of code showing how to do this conversion.

// Find the first wall in the project for testing
Element e = new FilteredElementCollector(doc).OfClass(typeof(Wall)).First();

string uniqueIDstring = e.UniqueId;
// a GUID such as 4f2cb6f4-bd46-4877-8bd9-3dae7acfdfae-0002d7f3

Element eFromString = doc.GetElement(uniqueIDstring);

string idFromString = e.Id.ToString();
// a string storing a value such as 186354

int idInt = Convert.ToInt32(idFromString);
ElementId id = new ElementId(idInt);
Element eFromId = doc.GetElement(id);

TaskDialog.Show("Elements", eFromString.Id + "\n" + eFromId.Id);
Advertisements

2 thoughts on “Getting an element from a string ID

  1. Hi Matt,
    How is it possible that I am querying for elementIds and i get 3 viewSection Ids that equal -1 ?

    cheers,
    Perplexed

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s