2

Accessing current workspace using an ArcObjects add-in for ArcMap (Table of Contents has layer groups).

I am trying to retrieve the current WorkSpace using ArcObjects for an ArcMap add-in in C#. Any help would be appreciated. I've tried this:

IWorkspace ws = ((IDataset)ArcMap.Document.ActiveView.FocusMap.Layer[0]).Workspace;

This works if the table of contents has no group layers.

Thanks

  • 3
    I wouldn't necessarily consider the workspace of the first layer to be the "current" layer. Maybe question should be re-phrased as "How to find the workspace of a layer?". – Kirk Kuykendall Jan 16 '13 at 0:44
2

It may work for you. CreateLayerList() method makes a list of layers of current map. It includes layers under group layers also.

    IWorkspace GetWorkspace()
    {
        var mapLayers = GetAllLayersFromMap();
        if(mapLayers.Count > 0)
            IWorkspace workspace =((IDataset)mapLayers[0]).Workspace;
    }

    List<ILayer> GetAllLayersFromMap()
    {
        var mapLayers = new List<ILayer>();

        CreateLayerList(null, _map, _map.LayerCount, mapLayers);
        return mapLayers;
    }

    void CreateLayerList(ICompositeLayer compositeLayer, IMap map, int mapCount, List<ILayer> mapLayers)
    {
        for (int i = 0; i < mapCount; i++)
        {
            ILayer layer;
            if (map != null && compositeLayer == null)
                layer = map.Layer[i];
            else if (compositeLayer != null)
                layer = compositeLayer.Layer[i];
            else
                return;
            ICompositeLayer comLayer;
            if (((comLayer = layer as ICompositeLayer) != null) && ((layer as IGroupLayer) != null))
                CreateLayerList(comLayer, null, comLayer.Count, mapLayers);
            else
                mapLayers.Add(layer);
        }
    }
|improve this answer|||||
  • Hi Guys thanks a lot for the help Rich and Emi works for me – Amo Jan 17 '13 at 15:16
  • Hi @Amo, if you get any answer helpful, you should give it a up vote :) – Emi Jan 18 '13 at 16:51
3

If you are on an edit session, it would be an option to get the IEditor.EditWorkspace which is an IWorkspace.

 UID editorUid = new UID();
 editorUid.Value = "esriEditor.Editor";
 IEditor3 editor = m_application.FindExtensionByCLSID(editorUid)as IEditor3;

 IWorkspace workspace = null;
 if(editor.EditState == esriStateEditing)
 {
    workspace = editor.EditWorkspace;
 }
|improve this answer|||||
2

A group layer is a coclass of ICompositeLayer. Use the count and layer properties of the ICompositeLayer interface to iterate through your group layers. So when you are looping through the TOC layers, check if the layer type is ICompositeLayer and then implement a sub loop through those layers as well.

|improve this answer|||||

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.