本文介绍了foreach控件C#跳过控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下循环删除C#Windows Forms应用程序中的按钮。唯一的问题是,它跳过了所有其他按钮。我该如何删除表单中的所有按钮控件?
I have the following loop to remove the buttons in my C# Windows Forms application. The only problem is that it skips every other button. How do I go about removing all the button controls from my form?
foreach (Control cntrl in Controls)
{
if(cntrl.GetType() == typeof(Button))
{
Controls.Remove(cntrl);
cntrl.Dispose();
}
}
推荐答案
I认为这种方式更具可读性:
I think this way is a bit more readable:
var controlsToRemove = Controls.OfType<Button>().ToArray();
foreach (var control in controlsToRemove)
{
Controls.Remove(control);
cntrl.Dispose();
}
调用 ToArray()
创建一个新的具体集合,以便您可以枚举一个并修改另一个。
Calling ToArray()
makes a new concrete collection, so that you can enumerate over one and modify the other.
这篇关于foreach控件C#跳过控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!