Based on pecoanddeco's answer, here is the VBA code converted to C#.
Note that you'll need to create the XYSample.txt
file and add it to your map as described here
Need to add the following ArcGIS References
- ESRI.ArcGIS.ArcMapUI
- ESRI.ArcGIS.CartoESRI
- ESRI.ArcGIS.CartoUI
- ESRI.ArcGIS.Display
- ESRI.ArcGIS.Framework
- ESRI.ArcGIS.Geodatabase
- ESRI.ArcGIS.Geometry
- ESRI.ArcGIS.LoctationUI
using ESRI.ArcGIS.ArcMapUI;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Framework;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.LocationUI;
void AddXYEventLayer()
{
IMxDocument mxdoc = ArcMap.Application.Document as IMxDocument;
IMap map = mxdoc.FocusMap;
// Get the table named XYSample.txt
IStandaloneTableCollection stTableCollection = map as IStandaloneTableCollection;
IStandaloneTable standaloneTable = null;
ITable table = null;
for (int i = 0; i < stTableCollection.StandaloneTableCount; i++)
{
standaloneTable = stTableCollection.StandaloneTable[i];
if (standaloneTable.Name == "XYSample.txt")
{
table = standaloneTable.Table;
break;
}
}
if (table == null)
{
MessageBox.Show("XYSample.txt table was not found in this map.");
return;
}
// Get the table name object
IDataset dataset = table as IDataset;
IName tableName = dataset.FullName;
// Specify the X and Y fields
IXYEvent2FieldsProperties xyEvent2FieldsProperties = new XYEvent2FieldsProperties() as IXYEvent2FieldsProperties;
xyEvent2FieldsProperties.XFieldName = "x";
xyEvent2FieldsProperties.YFieldName = "y";
xyEvent2FieldsProperties.ZFieldName = "";
// Specify the projection
ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironment() as ISpatialReferenceFactory;
IProjectedCoordinateSystem projectedCoordinateSystem = spatialReferenceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_NAD1983UTM_11N);
// Create the XY name object as set it's properties
IXYEventSourceName xyEventSourceName = new XYEventSourceName() as IXYEventSourceName;
xyEventSourceName.EventProperties = xyEvent2FieldsProperties;
xyEventSourceName.SpatialReference = projectedCoordinateSystem;
xyEventSourceName.EventTableName = tableName;
IName xyName = xyEventSourceName as IName;
IXYEventSource xyEventSource = xyName.Open() as IXYEventSource;
// Create a new Map Layer
IFeatureLayer featureLayer = new FeatureLayer() as IFeatureLayer;
featureLayer.FeatureClass = xyEventSource as IFeatureClass;
featureLayer.Name = "Sample XY Event Layer";
// Add the layer extension (this is done so that when you edit
// the layer's Source properties and click the Set Data Source
// button, the Add XY Events Dialog appears)
ILayerExtensions layerExtensions = featureLayer as ILayerExtensions;
XYDataSourcePageExtension resPageExtension = new XYDataSourcePageExtension();
layerExtensions.AddExtension(resPageExtension);
map.AddLayer(featureLayer);
}