dxman

10.1 Python Add-in: Combobox arcpy.SelectLayerBy onSelChange and onFocus error

Discussion created by dxman on Jun 19, 2013
Latest reply on Sep 23, 2013 by dxman
Hi all,

I am having a very odd issue with a 10.1 Python Add-in Combobox. The code below is taken from a much larger code set and is trying to make a selection in a layer, based on the unique value selected in the combobox. The unique values are loaded onFocus. The selection is made onSelChange. The issue involves any use of arcpy.SelectLayerByAttribute_management OR arcpy.SelectLayerByLocation_management within the onSelChange or onFocus events. When I open an mxd with existing layers, everything works great. However, as soon as I make a change to any layer in the TOC (ie turn a layer off or on), the tool fails. It fails on the SelectLayerBy consistently. It will fire the onFocus several times before failing when it attempts the SelectLayerBy. Again, if the layers exist within the mxd on load, everything works fine. It's just when a layer is added or properties changed from the TOC.

Any thoughts?
Thanks in advance

import arcpy
import pythonaddins

class cboxValue(object):
    """Implementation for temp_addin.combobox (ComboBox)"""
    def __init__(self):
        self.items = []
        self.editable = True
        self.enabled = True
        self.dropdownWidth = 'WWWWWWWWWWWWWWWWWWWWW'
        self.width = 'WWWWWWWWWWWWWWWW'
    def onSelChange(self, selection):
        mxd = arcpy.mapping.MapDocument('CURRENT')
        active_view = mxd.activeView
        df = arcpy.mapping.ListDataFrames(mxd, active_view)[0]
        lyr = arcpy.mapping.ListLayers(mxd, "Towns", df)[0]
        strValue = str(selection)
        strValue = strValue.replace("'", "''")
        strSQL = "\"OFF_NAME\" = '" + strValue + "'"
        arcpy.SelectLayerByAttribute_management(lyr, "NEW_SELECTION", strSQL)
    def onFocus(self, focused):
        if focused:
            self.items = []
            mxd = arcpy.mapping.MapDocument('CURRENT')
            active_view = mxd.activeView
            df = arcpy.mapping.ListDataFrames(mxd, active_view)[0]
            lyr = arcpy.mapping.ListLayers(mxd, "Towns", df)[0]
            valueSet = set()
            valueList = []
##            dfExtent = arcpy.Polygon(arcpy.Array([df.extent.lowerLeft, df.extent.lowerRight, df.extent.upperRight, df.extent.upperLeft]), df.spatialReference)
##            arcpy.SelectLayerByLocation_management(lyr, "INTERSECT", dfExtent)
            rows = arcpy.SearchCursor(lyr)
            for row in rows:
                value = row.getValue("OFF_NAME")
                if value not in valueSet:
                    valueSet.add(value)
            valueList = list(valueSet)
            valueList.sort()
            self.items = valueList

Outcomes