Programmatically change the data source of a layer in ArcMap
The sample code provided is to programmatically change a layer's data source in ArcMap.
Public Sub ChangeDataSource()
Dim pmxdoc As IMxDocument
Set pmxdoc = ThisDocument
Dim pmap As IMap
Set pmap = pmxdoc.ActiveView
Dim pfeatlayer As IFeatureLayer
Set pfeatlayer = pmap.Layer(0)
Dim pdatalayer As IDataLayer
Set pdatalayer = pfeatlayer
Dim pname As IName
Dim strTable As String
Dim strLocation As String
' Set the path to the directory containing the shapefile.
strLocation = "C:\testing\canada"
' Set the shapefile name to be used as the data source.
strTable = "provinces"
Dim pdatasetname As IDatasetName
Dim ptable As ITable
Dim pwrkspc As IWorkspaceName
Set pwrkspc = New WorkspaceName
pwrkspc.PathName = strLocation
' If a data source other than a shapefile is used,
' the workspace type will need to be changed.
pwrkspc.WorkspaceFactoryProgID = "esricore.shapefileworkspacefactory.1"
Set pdatasetname = New TableName
pdatasetname.Name = strTable
Set pdatasetname.WorkspaceName = pwrkspc
Set pname = pdatasetname
Set ptable = pname.Open
Dim pgeodataset As IGeoDataset
Set pgeodataset = ptable
Set m_penv = pgeodataset.Extent
Dim pfcname As IDatasetName
Set pfcname = pname
pdatalayer.DataSourceName = pname
Dim pav As IActiveView
Set pav = pmap
pav.Extent = m_penv
Set pav = pmap
pav.Refresh
End Sub
Dim pmxdoc As IMxDocument
Set pmxdoc = ThisDocument
Dim pmap As IMap
Set pmap = pmxdoc.ActiveView
Dim pfeatlayer As IFeatureLayer
Set pfeatlayer = pmap.Layer(0)
Dim pdatalayer As IDataLayer
Set pdatalayer = pfeatlayer
Dim pname As IName
Dim strTable As String
Dim strLocation As String
' Set the path to the directory containing the shapefile.
strLocation = "C:\testing\canada"
' Set the shapefile name to be used as the data source.
strTable = "provinces"
Dim pdatasetname As IDatasetName
Dim ptable As ITable
Dim pwrkspc As IWorkspaceName
Set pwrkspc = New WorkspaceName
pwrkspc.PathName = strLocation
' If a data source other than a shapefile is used,
' the workspace type will need to be changed.
pwrkspc.WorkspaceFactoryProgID = "esricore.shapefileworkspacefactory.1"
Set pdatasetname = New TableName
pdatasetname.Name = strTable
Set pdatasetname.WorkspaceName = pwrkspc
Set pname = pdatasetname
Set ptable = pname.Open
Dim pgeodataset As IGeoDataset
Set pgeodataset = ptable
Set m_penv = pgeodataset.Extent
Dim pfcname As IDatasetName
Set pfcname = pname
pdatalayer.DataSourceName = pname
Dim pav As IActiveView
Set pav = pmap
pav.Extent = m_penv
Set pav = pmap
pav.Refresh
End Sub
-----------------------------------------------------------
佛对我说:你心里有尘。我用力的拭擦。