简体   繁体   English

以编程方式删除控件未按预期工作

[英]Removing Controls programmatically NOT working as expected

I have 11 panels in each tabpage of a tabcontrol and want to remove 10 panels.我在 tabcontrol 的每个 tabpage 中有 11 个面板,并且想要删除 10 个面板。 so I wrote this code:所以我写了这段代码:

        var PnlsToRemove = tabControl.SelectedTab.Controls.OfType<Panel>()
            .Where(p => !p.Name.StartsWith("BasePanel"));
        foreach (var pnl in PnlsToRemove)
            pnl.Dispose();

but after tracing I wondered that remove order is alternate!但追踪后我想知道删除顺序是交替的!
means that when above code runs just panels 0,2,4,6,8,10 will remove and the others remains.意味着当上面的代码运行时,只有面板 0、2、4、6、8、10 将被移除,而其他面板将保留。
so I should put my code in a loop to remove panels alternately like this:所以我应该把我的代码放在一个循环中,像这样交替删除面板:

    while (tabControl.SelectedTab.Controls.OfType<Panel>().Count() != 1)
    {
        var PnlsToRemove = tabControl.SelectedTab.Controls.OfType<Panel>()
            .Where(p => !p.Name.StartsWith("BasePanel"));
        foreach (var pnl in PnlsToRemove)
            pnl.Dispose();
    }

in this case(for 10 panels) while() loops 4 times to remove all the panels.在这种情况下(对于 10 个面板)while() 循环 4 次以移除所有面板。

NOTICE: all of my panels exist in "PnlsToRemove" and this bug occurs on execution of "PnlsToRemove" in foreach.注意:我的所有面板都存在于“PnlsToRemove”中,并且在 foreach 中执行“PnlsToRemove”时会出现此错误。

So, what's wrong with my code?那么,我的代码有什么问题?
Why foreach() jumps from next panel?为什么foreach()从下一个面板跳转?

I think every thing is clear!我想一切都清楚了!

The underlying collection is being mutated as you remove the panels from the list, and this is apparently being reflected in the values seen by the "foreach".当您从列表中删除面板时,底层集合正在发生变化,这显然反映在“foreach”看到的值中。 The solution is to store the values into a new collection and iterate over that.解决方案是将值存储到一个新集合中并对其进行迭代。 You should be able to do this by adding a ".ToList()" to your definition of PnlsToRemove您应该能够通过在 PnlsToRemove 的定义中添加“.ToList()”来做到这一点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM