arcpy or pythonaddin - identify layers with a selection in the TOC

612
1
10-09-2013 07:28 PM
BobBaker1
New Contributor
I am looking for a way to identify what layers have a selection in the TOC.

I know this can be done in .NET. I have yet to see anything in python.

If anyone can help let me know!

Thank You,

- B
Tags (2)
0 Kudos
1 Reply
XanderBakker
Esri Esteemed Contributor
I am looking for a way to identify what layers have a selection in the TOC.

I know this can be done in .NET. I have yet to see anything in python.

If anyone can help let me know!

Thank You,

- B


Hi Bob,

It would be nice to have a short way of determining if a layer in the TOC has a selection (which is pretty straightforward with ArcObjects). I wrote a small piece of code and it seams to work as long as not all the features in a layer are selected:


import arcpy

mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd, "")[0]
lyrs = arcpy.mapping.ListLayers(mxd, "", df)

for lyr in lyrs:
    if lyr.isFeatureLayer:

        # this is the number of (selected) features in layer in TOC (in DefQuery)
        countSel = int(arcpy.GetCount_management(lyr).getOutput(0))

        # when there is a defintionQuery test features in query against 'selected' feature
        lyr2 = lyr.dataSource
        if lyr.definitionQuery == '':
            countDefQ = int(arcpy.GetCount_management(lyr2).getOutput(0))
        else:
            field = "OID@"
            countDefQ =0
            for row in arcpy.da.SearchCursor(lyr2, (field),where_clause=lyr.definitionQuery):
                countDefQ+=1

        # now test the counts
        if countSel == countDefQ:
            print "Layer '{0}' has no selection OR all features are selected".format(lyr.name)
        else:
            print "Layer '{0}' has a selection.  CountSel={1}  en  CountDefQ={2}".format(lyr.name,countSel,countDefQ)



I came across a much smaller snippet of Python code in an older post:

import arcpy

mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd, "")[0]
lyrs = arcpy.mapping.ListLayers(mxd, "", df)

for lyr in lyrs:
    if lyr.isFeatureLayer:

        selectionCount2 = int(arcpy.GetCount_management(arcpy.Describe(lyr).catalogpath).getOutput(0)) - int(arcpy.GetCount_management(lyr).getOutput(0))
        if selectionCount2 == 0:
            print "Layer '{0}' has no selection OR all features are selected".format(lyr.name)
        else:
            print "Layer '{0}' has a selection.  Difference={1}".format(lyr.name,selectionCount2)


The downside of this method is that it doesn't take the Definition Query into account. Maybe if both are mixed it can be done.
I think this would be a nice feature to have in a next release...

Kind regards,

Xander Bakker
0 Kudos