Hi,
I'm trying to do a spatial query on a layer in my map. In my code, I first check to see if the layer is there:
IEnumerable<Layer> gridLayer = map.GetLayersAsFlattenedList().Where(l => l.Name.IndexOf("GISWRKS1.WORKS.LAND_Grid", StringComparison.CurrentCultureIgnoreCase) >= 0);
if (gridLayer.Count() == 0)
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Please add the GRID layer before proceeding.", "Missing Layer");
return;
}
Later in the code I want to use a point to intersect the gridLayer using this code:
SpatialQueryFilter spatialFilter = new SpatialQueryFilter();
spatialFilter.FilterGeometry = intersectPoint;
spatialFilter.SpatialRelationship = SpatialRelationship.Intersects;
spatialFilter.SubFields = "GRIDNO";
FeatureLayer grid = (FeatureLayer)gridLayer; //This does not work. Null Reference Exception or sometimes an InvalidCast, depending on what I am doing. How do I turn my gridLayer from above into something I can use to query?? I've tried many different things...FeatureLayer, BasicFeatureLayer, FeatureClass.....nothing works.
RowCursor gridCursor = grid.Search(spatialFilter);
while (gridCursor.MoveNext())
{
using (Feature feature = (Feature)gridCursor.Current)
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(feature[0].ToString());
}
}
Solved! Go to Solution.
Brian,
The first line of your code defines gridLayer as a IEnumerable<Layer> ... you cannot cast an enumeration to a class that expects a single object.
It would be better if the line was something similar to this
Layer gridLayer = map.GetLayersAsFlattenedList().Where(l => l.Name.IndexOf("GISWRKS1.WORKS.LAND_Grid", StringComparison.CurrentCultureIgnoreCase) >= 0).FirstOrDefault();
then you can check gridLayer against null to determine if it exists. Finally you can then do
FeatureLayer grid = gridLayer as FeatureLayer;
Alternatively you could also do this
FeatureLayer gridLayer = map.GetLayersAsFlattenedList().OfType<FeatureLayer>().Where(l => l.Name.IndexOf("GISWRKS1.WORKS.LAND_Grid", StringComparison.CurrentCultureIgnoreCase) >= 0).FirstOrDefault();
Brian,
The first line of your code defines gridLayer as a IEnumerable<Layer> ... you cannot cast an enumeration to a class that expects a single object.
It would be better if the line was something similar to this
Layer gridLayer = map.GetLayersAsFlattenedList().Where(l => l.Name.IndexOf("GISWRKS1.WORKS.LAND_Grid", StringComparison.CurrentCultureIgnoreCase) >= 0).FirstOrDefault();
then you can check gridLayer against null to determine if it exists. Finally you can then do
FeatureLayer grid = gridLayer as FeatureLayer;
Alternatively you could also do this
FeatureLayer gridLayer = map.GetLayersAsFlattenedList().OfType<FeatureLayer>().Where(l => l.Name.IndexOf("GISWRKS1.WORKS.LAND_Grid", StringComparison.CurrentCultureIgnoreCase) >= 0).FirstOrDefault();
Ah yes, that makes sense to me now. Thanks for helping!!