English

How To: Change between the Display and Source tabs in the ArcMap Table of Contents (TOC) with ArcObjects

Summary

The following code shows how to change focus between one ArcMap Table of Contents (TOC) view and another. The standard views include Data and Source, but this code will also work for custom TOC views.

Procedure

  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. If you want to store the code in all your map documents, open the Normal.mxt ThisDocument code module instead.

  4. Copy the following code into the code module.
    Code:
    Public Sub test()
    ' change to "Display" if you wish to switch to the Display tab.
    ChangeArcMapTOC_ContentsView ("Source")
    End Sub

    Private Sub ChangeArcMapTOC_ContentsView(newContentsViewName As String)
    On Error GoTo cantChangeView
    ' exit if trying to change to the current view.
    Dim pMxDoc As IMxDocument
    Set pMxDoc = ThisDocument
    If pMxDoc.CurrentContentsView.Name = newContentsViewName Then
    Exit Sub
    End If
    ' loop thru all ContentsViews to see if newContentsViewName exists.
    Dim i As Integer
    Dim pContentView As IContentsView
    Dim bFound As Boolean
    For i = 0 To pMxDoc.ContentsViewCount - 1
    Set pContentView = pMxDoc.ContentsView(i)
    If pContentView.Name = newContentsViewName Then
    bFound = True
    Exit For
    End If
    Next
    If bFound = False Then
    MsgBox "Contents view '" & newContentsViewName & "' does not exist", _
    vbExclamation, "Could not change contents view"
    Exit Sub
    Else
    Set pMxDoc.CurrentContentsView = pContentView
    End If
    Exit Sub
    cantChangeView:
    MsgBox Err.Description, vbExclamation, "Could not change contents view"
    Exit Sub
    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.