2

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);
            pa.Add(p[i]);
        }


        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;
        fCur.InsertFeature(buff);

        fCur.Flush();
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(fCur);
        ILayer layer =FC as ILayer;
        axMapControl1.AddLayer(layer);

        axMapControl1.Refresh();

1 Answer 1

2

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;
axMapControl1.AddLayer(l);

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

2
  • 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?) Commented Jan 25, 2016 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. Commented Jan 25, 2016 at 11:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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