Get Index Number from Layer Name Snippet (ArcObjects .NET 10.6 SDK)
ArcObjects Library Reference

Get Index Number from Layer Name Snippet

Get the index number for the specified layer name.

[C#]
///<summary>Get the index number for the specified layer name.</summary>
/// 
///<param name="activeView">An IActiveView interface</param>
///<param name="layerName">A System.String that is the layer name in the active view. Example: "states"</param>
///  
///<returns>A System.Int32 representing a layer number</returns>
///  
///<remarks>Return values of 0 and greater are valid layers. A return value of -1 means the layer name was not found.</remarks>
public System.Int32 GetIndexNumberFromLayerName(ESRI.ArcGIS.Carto.IActiveView activeView, System.String layerName)
{
  if(activeView == null || layerName == null)
  {
    return -1;
  }
  ESRI.ArcGIS.Carto.IMap map=activeView.FocusMap; 

  // Get the number of layers
  int numberOfLayers=map.LayerCount;

  // Loop through the layers and get the correct layer index
  for (System.Int32 i=0; i < numberOfLayers; i++)
  {
    if (layerName == map.get_Layer(i).Name)
    {

      // Layer was found
      return i;
    }
  }

  // No layer was found
  return -1;
}
[Visual Basic .NET]
'''<summary>Get the index number for the specified layer name.</summary>
''' 
'''<param name="activeView">An IActiveView interface</param>
'''<param name="layerName">A System.String that is the layer name in the active view. Example: "states"</param>
'''  
'''<returns>A System.Int32 representing a layer number</returns>
'''  
'''<remarks>Return values of 0 and greater are valid layers. A return value of -1 means the layer name was not found.</remarks>
Public Function GetIndexNumberFromLayerName(ByVal activeView As ESRI.ArcGIS.Carto.IActiveView, ByVal layerName As System.String) As System.Int32

  If activeView Is Nothing OrElse layerName Is Nothing Then
    Return -1
  End If

  Dim map As ESRI.ArcGIS.Carto.IMap=activeView.FocusMap

  ' Get the number of layers
  Dim numberOfLayers As System.Int32=map.LayerCount

  ' Loop through the layers and get the correct layer index
  Dim i As System.Int32=0

  Do While i < numberOfLayers

    If layerName=map.Layer(i).Name Then
      
      ' Layer was found
      Return i
    End If
    
    i += 1

  Loop

  ' No layer was found
  Return -1

End Function

Additional Requirements
  • The code in this document requires the following References added to the Visual Studio project:
  • ESRI.ArcGIS.Carto