I'm trying to use the following code in an ArcMap 10.1 extension:
private IFeatureLayer getLayer(string lname)
{
IMap map;
IFeatureLayer flayer;
IEnumLayer layerTag;
ILayer layer;
try
{
map = ArcMap.Document.FocusMap;
layerTag = map.Layers;
layer = layerTag.Next();
while (layer != null)
{
flayer = (IFeatureLayer) layer;
if (flayer.Name.Equals(lname))
{
if(validateFeatureClass(flayer.FeatureClass)){
flayer.Visible = true;
flayer.Selectable = true;
return flayer;
}
}
layer = layerTag.Next();
}
return null;
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.ToString(), "Exception", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return null;
}
}
but it hits the skids (throws a cast exception) when I try to use flayer = (IFeatureLayer) layer;
I had before flayer = layer as IFeatureLayer
but then name checking line failed due to a null reference exception.
Am I missing something obvious here?
flayer = layer as IFeatureLayer
and then do the null check--it certainly is possible and likely, that you will have layers in your map document that don't implement IFeatureLayer (like a raster layer or image service layer).if (layer is IFeatureLayer) { flayer = (IFeatureLayer) layer; }