How to change the data source of a layer


This code example illustrates how you can change the datasource of a layer. It changes the data source of the first layer in the selected dataframe.

How to use

  1. Reference the following Assemblies: ESRI.ArcGIS.Carto, ESRI.ArcGIS.Display, ESRI.ArcGIS.Geometry
  2. Add the 'node' feature class of the ..\SampleMaps\Data\JoshuaTreeNP\roads coverage as a layer.
  3. Change the location of the coverage workspace to correspond to your ArcGIS installation.
  4. Run the procedure.
[VBA]
Public Sub SetDataSource()
    Dim pWorkspaceFactory As IWorkspaceFactory
    Dim pWorkspace As IWorkspace
    Dim pFWorkspace As IFeatureWorkspace
    Dim pNewFC As IFeatureClass
    Dim pOldFC As IFeatureClass
    Dim pFCContainer As IFeatureClassContainer
    
    'Get FeatureClass to be set as datasource
    Set pWorkspaceFactory = New ArcInfoWorkspaceFactory
    Set pWorkspace = pWorkspaceFactory.OpenFromFile("D:\ArcGIS\SampleMaps\Data\JoshuaTreeNP", 0)
    Set pFWorkspace = pWorkspace
    Set pFCContainer = pFWorkspace.OpenFeatureDataset("roads")
    Set pNewFC = pFCContainer.ClassByName("arc")
    
    'Get current FeatureClass of first layer
    Dim pMxDoc As IMxDocument
    Dim pMap As IMap
    Dim pActiveView As IActiveView
    Dim pMapAdmin2 As IMapAdmin2
    Dim pFLayer As IFeatureLayer
    Set pMxDoc = ThisDocument
    Set pMap = pMxDoc.FocusMap
    Set pMapAdmin2 = pMap
    Set pActiveView = pMap
    Set pFLayer = pMap.Layer(0)
    Set pOldFC = pFLayer.FeatureClass
    
    'Change FeatureClass of layer
    Set pFLayer.FeatureClass = pNewFC
    pMapAdmin2.FireChangeFeatureClass pOldFC, pNewFC
    pActiveView.Refresh
    
    'Update and Refresh TOC
    Dim pFDataset As IFeatureDataset
    Set pFDataset = pFCContainer
    pFLayer.Name = pFDataset.Name & " " & pNewFC.AliasName
    pMxDoc.CurrentContentsView.Refresh 0
End Sub