This sample relates the attributes of the first table in the table of contents to the first layer in the table of contents in ArcMap. You will be prompted for the relate field which must be named the same in both the layer and table for the purposes of this sample. This sample performs the same function as the relate command from the layer context menu.
Once the relate is completed, you will be able to see it listed in the Joins and Relates tab of layer properties.
How to use
- Paste the function into your code.
- Make sure that the first layer and the first table in the tableof contents are the ones that you want to relate. Optionally, you can modifythe code to specify the proper layer and table.
- Execute the routine.
- When prompted, provide the name of the relate column which mustbe in both the layer and the table. You can later modify the code to allow differentrelate column names.
Public Sub RelateTabletoLayer()
On Error GoTo EH
Dim pDoc As IMxDocument
Dim pMap As IMap
Set pDoc = ThisDocument
Set pMap = pDoc.FocusMap
' Get the first layer in the table on contents
Dim pFeatLayer As IFeatureLayer
Dim pDispTable As IDisplayTable
Dim pFCLayer As IFeatureClass
Dim pTLayer As ITable
If pMap.LayerCount = 0 Then
MsgBox "Must have at least one layer"
Exit Sub
End If
Set pFeatLayer = pMap.Layer(0)
Set pDispTable = pFeatLayer
Set pFCLayer = pDispTable.DisplayTable
Set pTLayer = pFCLayer
' Get the first table in the table on contents
Dim pTabCollection As IStandaloneTableCollection
Dim pStTable As IStandaloneTable
Dim pDispTable2 As IDisplayTable
Dim pTTable As ITable
Set pTabCollection = pMap
If pTabCollection.StandaloneTableCount = 0 Then
MsgBox "Must have atleast one table"
Exit Sub
End If
Set pStTable = pTabCollection.StandaloneTable(0)
Set pDispTable2 = pStTable
Set pTTable = pDispTable2.DisplayTable
' Prompt for the join field, in this example both joined
' fields must be named the same.
Dim strJnField As String
strJnField = InputBox("Provide the name of the join field:", "Joining a table to a layer", _
"FIPS_CODE")
' Create virtual relate
Dim pMemRelFact As IMemoryRelationshipClassFactory
Dim pRelClass As IRelationshipClass
Set pMemRelFact = New MemoryRelationshipClassFactory
Set pRelClass = pMemRelFact.Open("TabletoLayer", pTTable, strJnField, pTLayer, _
strJnField, "forward", "backward", esriRelCardinalityOneToMany)
' Add it to the relates for the feature layer in Map
Dim pRelClassCollEdit As IRelationshipClassCollectionEdit
Set pRelClassCollEdit = pFeatLayer
pRelClassCollEdit.AddRelationshipClass pRelClass
Exit Sub
EH:
MsgBox Err.Number & " " & Err.Description
End Sub