2

I currently have a Sharepoint 2010 web part which includes several labels. I want to programmatically remove all but one of these labels.

I tried the code below but got a System.InvalidOperationException because obviously one can't modify a collection while iterating through it. However, I don't know how else to try this.

    private void clearLabels()
    {
        foreach (Control cont in this.Controls)
            if (cont is Label && cont.ID != "error")
                this.Controls.Remove(cont);
    }
Landric
  • 271
  • 1
  • 6
  • 22

2 Answers2

5

Iterate over it backwards.

for(int i = this.Controls.Count - 1; i >= 0; i--)
{
    if (this.Controls[i] is Label && this.Controls[i].ID != "error")
    {
        this.Controls.Remove(this.Controls[i]);
    }
}
canon
  • 40,609
  • 10
  • 73
  • 97
1

You are correct as to why you are getting the error. The following using Linq and ToArray() to solve the problem:

private void clearLabels()
    {
        foreach (from cont in this.Controls).ToArray()
            if (cont is Label && cont.ID != "error")
                this.Controls.Remove(cont);
    }

I would refactor this even further to:

private void clearLabels() {

    foreach (from cont in this.Controls 
             where cont is Label && cont.ID != "error"
            ).ToArray()
        this.Controls.Remove(cont);
}
Tim Murphy
  • 4,892
  • 4
  • 40
  • 48