Get the OID of a selected record?

1294
4
07-09-2013 05:55 AM
ionarawilson1
Occasional Contributor III
I need to have a record selected for the user to enter some attributes, then I need to deselect to calculate a unique id for the record (I only know how to calculate the unique id for all the records and that;s why I need to deselect it), then I need to continue updating that record that was selected before. For that I need to capture the OID of the selected record before I deselect it. I was able to write something to get the OID, but it gets the OID for all the records. Does anybody know how to get the OID for just the selected record? Thank you! Here is my snippet:

    # Create search cursor for feature class.     rows = gp.SearchCursor("Stewardship")     row = rows.Next()     while row:         # Get the ID value         desc = arcpy.Describe("Stewardship")         OIDFieldName = desc.OIDFieldName         id = row.GetValue(OIDFieldName)         arcpy.AddMessage(id)         row = rows.next() 
Tags (2)
0 Kudos
4 Replies
ionarawilson1
Occasional Contributor III
Never mind, this works if I have only one selected! Thanks
0 Kudos
RhettZufelt
MVP Frequent Contributor
glad to see you got it working.

I noticed that you have:

        desc = arcpy.Describe("Stewardship")
        OIDFieldName = desc.OIDFieldName


within the while loop.  the Describe function can be pretty intensive operation and I don't see a need to set it within the loop.

I suspect it would run considerably faster if you were to move these two lines above and out of the while loop.

R_
0 Kudos
ChrisSnyder
Regular Contributor III
Two other ways to get a list of OIDs of selected records (method #2 is the best BTW):


#Method1: Must have a selection on the feature layer for this to work... but works in any version
fc = r"C:\csny490\overlay_20130620\gis_layers\county.gdb\county"
arcpy.MakeFeatureLayer_management(fc, "fl")
arcpy.SelectLayerByAttribute_management("fl", "NEW_SELECTION", "COUNTY_CD > 10")
oidList = [int(oid) for oid in arcpy.Describe("fl").FIDSet.split(";")]
#Method2: Uber fast! Works with a feature layer with a definition query and/or selected set... but only in v10.1+!
fc = r"C:\csny490\overlay_20130620\gis_layers\county.gdb\county"
arcpy.MakeFeatureLayer_management(fc, "fl", "COUNTY_CD > 10")
oidList = [oid[0] for oid in arcpy.da.SearchCursor("fl",["OID@"])]
0 Kudos
ionarawilson1
Occasional Contributor III
Thank you Chris and Rhett! You guys are awesome!
0 Kudos