[英]How to remove buttons that were procedurally generated
I generate a number of buttons within my winform based on what is in a list this works fine, however I need to reset the form back to having none of the new buttons existing. 我会根据可以正常工作的列表中的内容在winform中生成许多按钮,但是我需要将表单重置为不存在任何新按钮。
The button generating code is: 按钮生成代码为:
private int importButtonFactory()
{
int numberOfButtons = 0;
int top = 70;
int left = 12;
foreach (Import import in ImportList)
{
Button importButton = new Button();
importButton.Left = left;
importButton.Top = top;
importButton.Width = 220;
this.Controls.Add(importButton);
top += importButton.Height + 2;
numberOfButtons++;
importButton.Text = import.Mapping;
importButton.Click += (object sndr, EventArgs c_args) => openFile_Click(import.Path);
}
return numberOfButtons;
}
I have tried following within a separate function: 我已经尝试在一个单独的函数中执行以下操作:
Controls.Remove(importButton);
But I get the error: "The name 'importButton' does not exist in the current context"
但我收到错误消息:
"The name 'importButton' does not exist in the current context"
Yes and that's cause the control instance declared inside a different function. 是的,这导致控件实例在其他函数中声明。 You can create a
List<Button>
and have them clear later like 您可以创建一个
List<Button>
并稍后将其清除,例如
List<Button> buttonList = new List<Button>();
private int importButtonFactory()
{
int numberOfButtons = 0;
foreach (Import import in ImportList)
{
Button importButton = new Button();
....
buttonList.Add(importButton);
}
In your other method you can access the list and remove them 您可以使用其他方法访问列表并将其删除
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.