[GIS] Zooming to selected features with ArcObjects

arcobjectscextentsfeaturesselect-by-attribute

I am trying to figure out how to set the active view extent to be able to view all the selected features on the ArcMap.

  1. The Map has only one layer.
  2. The features are filtered with attributes.

Below is the code where I tried,stuck with the part where I can loop through the features in
the feature selection set but not able to set the active view extent to zoom to show all the selected ones.

This is similar to doing the right click on the attributes table and selecting multiple rows and doing a Zoom to selected.

private void ZoomToMultipleDGVSelection(List<int> selectedRightIDs)
    {

        IMxDocument pMxDoc = ArcMap.Document;
        IMap pMap = (IMap)pMxDoc.ActiveView;

        ESRI.ArcGIS.Carto.ILayer layer = GetLayersClass.GetFieldBoundaryLayer;
        if (layer is ESRI.ArcGIS.Carto.IGroupLayer)
        {

            ESRI.ArcGIS.Carto.IGroupLayer groupLayer = layer as    ESRI.ArcGIS.Carto.IGroupLayer;
            ICompositeLayer pCompositeLayer = layer as ICompositeLayer;
            int layers = pCompositeLayer.Count;
            ILayer pLayer = pCompositeLayer.Layer[0];
            IFeatureLayer pFeatureLayer = (IFeatureLayer)pLayer;

            IFeatureSelection pFeatureSelection = (IFeatureSelection)pLayer;
            ISelectionSet pSelectionSet = pFeatureSelection.SelectionSet;

            IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
            IQueryFilter pFilter = new QueryFilterClass();

            foreach(int ID  in selectedRightIDs)
            {
            pFilter.WhereClause = "RightID = " + ID.ToString();

            IFeatureCursor pFeatureCursor = pFeatureClass.Search(pFilter, false);
            IFeature pFeature = pFeatureCursor.NextFeature();

            pFeatureSelection.Add(pFeature);

            }


            //if (pFeature == null)
            //{
            //    System.Windows.Forms.MessageBox.Show("This section doesn't exist");
            //    return;
            //}


            IGeometry pgeom = (IGeometry)pFeature.Shape;
            pMap.SelectByShape(pgeom, null, false);
            IEnvelope pEnv = pgeom.Envelope;
            pMxDoc.ActiveView.Extent = pEnv;
            pMxDoc.ActiveView.Refresh();
        }
    }

Best Answer

You could use the build-in command to Zoom to Selected features. This is from the Find Command and Execute Snippet

public void FindCommandAndExecute(ESRI.ArcGIS.Framework.IApplication application, System.String commandName)
{
  ESRI.ArcGIS.Framework.ICommandBars commandBars = application.Document.CommandBars;
  ESRI.ArcGIS.esriSystem.UID uid = new ESRI.ArcGIS.esriSystem.UIDClass();
  uid.Value = commandName; // Example: "esriArcMapUI.MxSelectionMenu" or "{AB073B49-DE5E-11D1-AA80-00C04FA37860}"
  ESRI.ArcGIS.Framework.ICommandItem commandItem = commandBars.Find(uid, false, false);

  if (commandItem != null)
    commandItem.Execute();
}