Having trouble converting an Ilayer to an IPolygon.
I am developing a toolbar for ArcMap and I grab a layer via code from the side table of contents. The Layer is a Polygon, but the code won't convert it to a IPolygon.
Can anyone help me out? This is the code I am using to try and convert it to a IPolygon...
IPolygon poly = m_document.Maps.get_Item(0).get_Layer(0) as IPolygon;
I can do this:
ILayer layer = m_document.Maps.get_Item(0).get_Layer(0) as ILayer;
And that works, just not converting it to a IPloygon..
If you want to access the geometries contained in a shapefile layer, you have to get the layer's feature class. This is a property of the IFeatureLayer interface, so you'll have to cast your layer (which is an ILayer) first:
IFeatureLayer FLayer = layer as IFeatureLayer;
IFeatureClass FClass = FLayer.FeatureClass;
If you have a feature class, you can get features by index (slow) or by defining a cursor on the feature class (this is fast and the preferred way when you want to handle lots of features. Search for IFeatureCursor; ESRI docs usualy come with good code snippets).
If your feature class contains only one feature, or if you only want one feature, You can use the GetFeature method:
IFeature MyFeature = FClass.GetFeature(0);
Now you're almost there. A feature's geometry is tucked away in its Shape property:
IPolygon MyPoly = MyFeature.Shape as IPolygon;
The extra cast is needed because the Shape property is an IPolygon, which is a more specific IGeometry.