Removing a leyer by code

Nov 5, 2014 at 3:46 PM
Hi,I want to remove a layer from map..I use this code but I face an error..Can you help me find my mistake?
>  foreach (var item in map.Layers)
                          if (item.DataSet != null && item.DataSet.Name == "USE2000Layer")
                            item.IsVisible = false;
I got an error in this part of code
        /// <summary>
        /// Moves to the next member
        /// </summary>
        /// <returns>boolean, true if the enumerator was able to advance</returns>
        public bool MoveNext()
            while (_internalEnumerator.MoveNext())
                var result = _internalEnumerator.Current as IMapLayer;
                if (result != null) return true;
            return false;
It says enumerator is changed ..and It stops me working..Can you give me a better method to remove a layer from map?
Nov 5, 2014 at 5:08 PM
Hey am2,

as far as I can see you're using the correct methode to remove the layer. But you should never use for each if you want to remove something from a list.
Do it this way:
for (var i = map.Layers.Count-1; i >= 0; i--)
  if (map.Layers[i].DataSet != null && map.Layers[i].DataSet.Name == "USE2000Layer")
      map.Layers[i].IsVisible = false;
Foreach relies on an internal counter with a certain length. If you remove an item and go to the next, the list is one item shorter than the counter expects and you get an error. If you remove things from the end of the list it's all the same whether the list became shorter because all the items at the beginning are still there and thats where your going.

Nov 5, 2014 at 7:29 PM
Dear jany_
Thanks for your help..Yes it is my mistake that I used foreach in this case,I just wanted to find spacial layer and remove it from list of layers

I'll try your code.Thank you very much