简体   繁体   English

从C#窗体中删除控件

[英]Removing Controls From a Form C#

I created some user controls that I place on a form programmatically in VS 2013. Those controls need to be deleted and recreated on occasion. 我创建了一些用户控件,这些控件在VS 2013中以编程方式放置在窗体上。这些控件有时需要删除并重新创建。 I have tried deleting the controls two different ways. 我尝试了两种不同的方式删除控件。 One works, one doesn't. 一种有效,一种无效。 I'm hoping someone can provide insight as to why the one does not work. 我希望有人能提供关于为何该方法不起作用的见解。

This version does NOT work (it only finds two out of four controls): 此版本不起作用(只能在四个控件中找到两个):

// delete user controls from the front panel
foreach (UserControl ctrl in this.Controls.OfType<StationControl>())
{
    this.Controls.Remove(ctrl);
}

This version does work (it finds four out of four controls): 此版本确实有效(它在四个控件中找到四个):

// delete user controls from the front panel
var uc_list = this.Controls.OfType<StationControl>().ToArray();
foreach (var ctrl in uc_list)
{
    this.Controls.Remove(ctrl);
}

I can count the number of user controls matching the type without issue (eg 我可以算出与类型匹配的用户控件的数量,例如

int controlCount = this.Controls.OfType<StationControl>().Count()

So why does the first foreach statement not fully work? 那么为什么第一个foreach语句不能完全起作用?

Will this work? 这样行吗?

foreach (UserControl ctrl in this.Controls.OfType<StationControl>())
{
    ctrl.Dispose();
    this.Controls.Remove(ctrl);
}

I hope this helps. 我希望这有帮助。

Edit: 编辑:

The above won't work properly, here is a working approach: 上面的方法无法正常工作,这是一种可行的方法:

while (this.Controls.OfType<StationControl>().Count() > 0)
{
    UserControl ctrl = this.Controls.OfType<StationControl>().First();

    ctrl.Dispose();
    this.Controls.Remove(ctrl);
}

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

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