English

How To: Select a layer in the Table of Contents of ArcMap using ArcObjects

Summary

It is possible to programmatically make a layer selected in the Table of Contents by using IContentsView::AddToSelectedItems. The result is the same as clicking the layer in the GUI; the layers will turn blue.

Procedure

Instructions provided demonstrate how to make all layers in the data frame selected. Note the Display tab must be active.

  1. Start ArcMap.
  2. Open the Visual Basic Editor.

    In ArcMap, select Tools > Macros > Visual Basic Editor.

  3. In the Project Explorer window, expand Project.mxt and select ArcMap Objects > ThisDocument then right-click and select View Code.
    [O-Image] Visual Basic Project  Explorer
    Note:
    Code in the Project's ThisDocument code module will only run in the current map document. To store the code in all map documents open the Normal.mxt ThisDocument code module instead.

  4. Copy the following code into the code module.

    Code:
    Sub SelectLayersInDisplayView()

    ' selects all of the layers in the first data frame in the toc's display view

    Dim pMxDoc As IMxDocument
    Set pMxDoc = ThisDocument
    Dim ptoc As IContentsView
    Set ptoc = pMxDoc.ContentsView(0) ' Display View

    Dim pMaps As IMaps
    Set pMaps = pMxDoc.Maps
    Dim pMap As IMap

    Dim i As Integer
    Set pMap = pMaps.Item(0) ' first data frame
    Dim pEnumLayer As IEnumLayer
    Set pEnumLayer = pMap.Layers
    Dim pLayer As ILayer
    Set pLayer = pEnumLayer.Next

    ptoc.RemoveFromSelectedItems ptoc.SelectedItem
    Do While Not pLayer Is Nothing
    ptoc.AddToSelectedItems pLayer
    ptoc.Refresh pLayer
    Set pLayer = pEnumLayer.Next
    Loop

    End Sub

  5. Close the Visual Basic Editor.
  6. Run the code.

    A. Click Tools > Macros > Macros to display the Macros dialog box.
    B. Select a macro and click Run.