I am trying to get the selected features from axMapControl and put them in a new feature class. I can get the selected features but when i'm trying to put them in a IFeatureClass and then cast it as IFeatureLayer I get the null reference exception.

Can any one help?

List<IFeature> features = GetSelectedFeatures(axMapControl1.get_Layer(0) as IFeatureLayer);
        IPointArray pa = new PointArrayClass();
        for (int i = 0; i < features.Count; i++)
            p.Add(features[i].ShapeCopy as IPoint);

        IPolyline pl = new PolylineClass();
        pl.FromPoint = pa.Element[0];
        pl.ToPoint = pa.Element[1];
        pl.ToPoint = pa.Element[2];

        pl.SpatialReference = p[0].SpatialReference;

        IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass();
        IWorkspace workspace = workspaceFactory.OpenFromFile(@"C:\", 0);
        IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace;

        IFeatureClass FC = CreateFeatureClass("FC", featureWorkspace, pa.get_Element(0).SpatialReference);

        IFeatureCursor fCur = FC.Insert(false);
        IFeatureBuffer buff = FC.CreateFeatureBuffer();

        buff.Shape = pl;

        ILayer layer =FC as ILayer;


You can not cast a FeatureClass into a ILayer! Here's the proper way to reach an ILayer from a FeatureClass:

IFeatureLayer fl = new ESRI.ArcGIS.Carto.FeatureLayer() 
fl.FeatureClass  = FC;
var l = fl as ILayer;

I am assuming all of your previous methods are correct and you have a valid IFeatuerClass (FC).

  • now i have another problem, in the same code when i use IPoint instead of IPolyline I get the error "Geometry cannot have Z values." what is this? (should I ask this in another question?) – Steve Jan 25 '16 at 7:34
  • Mohammad, as per GIS SE tour you should ask one question per post. So yes please feel free to ask another question. – Farid Cheraghi Jan 25 '16 at 11:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.