Removing all but one item from Controls [duplicate]

拥有回忆 提交于 2019-12-22 17:52:11

问题


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);
    }

回答1:


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]);
    }
}



回答2:


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);
}


来源:https://stackoverflow.com/questions/6664562/removing-all-but-one-item-from-controls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!