Add A Shapefile To A Map
Add A Shapefile To A Map
Description
This sample, which can easily be changed to support different data types, opens
a shapefile on your local disk and adds the contents to the map as a featurelayer.
In this sample, you will be adding a control button and writing the code for it.
How to use
1. Start ArcMap.
2. Open an existing map document (.mxd) or add layers to the empty (Untitled) map
document.
3. Click Tools and click Customize.
4. Click the Commands tab.
5. Click the drop-down arrow on the Save in combo box and click the map document in which
the new command will be saved.
6. Scroll through the Categories list and click [UIControls].
7. Click New UIControl.
8. Click to select the UIButtonControl as the UIControl Type.
9. Click Create.
10. Click and drag the new Project.UIButtonControl1 in the Commands list and drop it on any
toolbar.
11. Click Close.
12. Right-click the newly placed control and click View Source.
This opens the Visual Basic Editor.
13. In the ThisDocument (Code) window, click the Procedure Box drop-down arrow (the one on
the right of the window) and choose Click.
This adds the wrapper code for the procedure you are creating.
14. Copy and paste the following code between the two wrapper code lines (between Private
Sub UIButtonControl1_Click() and End Sub).
Dim pWorkspaceFactory As IWorkspaceFactory
Set pWorkspaceFactory = New ShapefileWorkspaceFactory
Dim pWorkSpace As IFeatureWorkspace
'Change C:\Source to the source location of the shapefile you wish to add
Set pWorkSpace = pWorkspaceFactory.OpenFromFile("C:\Source", 0)
Dim pClass As IFeatureClass
'Change USStates to the name of the shapefile you wish to add
Set pClass = pWorkSpace.OpenFeatureClass("USStates")
Dim pLayer As IFeatureLayer
Set pLayer = New FeatureLayer
Set pLayer.FeatureClass = pClass
pLayer.Name = pClass.AliasName
Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument
pMxDoc.AddLayer pLayer
pMxDoc.ActiveView.PartialRefresh esriViewGeography, pLayer, Nothing
15. Go to line 5, Set pWorkSpace = pWorkspaceFactory.OpenFromFile("C:\Source", 0), and
change C:\Source to the source location of the shapefile you want to add.
16. Go to line 8, Set pClass = pWorkSpace.OpenFeatureClass("USStates"), and change
USStates to the name of the shapefile you want to add.
17. Close the Visual Basic Editor.
18. Click the new button in ArcMap to add the feature class to the map.
Tip
Make sure the code in Visual Basic appears as it does in the above steps. For example, you may
have to add carriage returns.