.NET 2
// dynamic textbox adding
myTextBox = new TextBox();
this.Controls.Add(myTextBox);
// ... some code, finally
// dynamic textbox removing
myTextBox.Dispose();
// this.Controls.Remove(myTextBox); ?? is this needed
Run Code Online (Sandbox Code Playgroud)
按照这个问题Foreach循环处理控件跳过迭代它告诉我,迭代是允许通过更改集合:
例如,以下内容:
List<Control> items = new List<Control>
{
new TextBox {Text = "A", Top = 10},
new TextBox {Text = "B", Top = 20},
new TextBox {Text = "C", Top = 30},
new TextBox {Text = "D", Top = 40},
};
foreach (var item in items)
{
items.Remove(item);
}
Run Code Online (Sandbox Code Playgroud)
投
InvalidOperationException:Collection已被修改; 枚举操作可能无法执行.
但是,在.Net表单中,您可以执行以下操作:
this.Controls.Add(new TextBox {Text = "A", Top = 10});
this.Controls.Add(new TextBox {Text = "B", Top = 30});
this.Controls.Add(new TextBox {Text = "C", Top = 50});
this.Controls.Add(new …Run Code Online (Sandbox Code Playgroud) 我有以下循环来删除我的C#Windows窗体应用程序中的按钮.唯一的问题是它会跳过其他所有按钮.如何从表单中删除所有按钮控件?
foreach (Control cntrl in Controls)
{
if(cntrl.GetType() == typeof(Button))
{
Controls.Remove(cntrl);
cntrl.Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)