我有两个表单,当Form1个负载时,它显示Form2:

Form frm = new Form2();

public Form1()
{
    InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
    frm.Show();
}

Form1有一个按钮,可以在Form2上动态创建10个按钮.

private void btnCreateButtons_Click(object sender, EventArgs e)
{
    for (int t=0;t<10;t++)
    {
        Button button = new Button();
        button.Text = "Button " + t.ToString();
        button.Location = new Point(10, (10+(button.Height*t)));
        frm.Controls.Add(button);
    }
}

这里是点击一次[创建按钮]后的两个表格.

create dynamic buttons


然后,目标是当在Form1上单击[Dispose]按钮时,它将正确地删除并处理在第一步中创建的Form2上的所有按钮.但我有一个问题,销毁动态对象创建.

private void btnDisposeAll_Click(object sender, EventArgs e)
{
    foreach(Control control in frm.Controls)
    {
        if (control != null)
        {
            this.Controls.Remove(control);
            control.Dispose();
        }
    }
}

当我想销毁这个动态按钮时,Dispose方法不能正常工作.只有Form2个动态按钮中的一些会消失.

destroy buttons

我的代码出了什么问题? 谢谢

推荐答案

我能够从你的代码中重现这种行为.我认为问题来自于在更改集合的同时迭代ControlCollection.要避免此问题,请将其转换为一个数组,该数组将使您免受更改的影响.

public partial class Form1 : Form
{
    Form frm = new Form2();
    public Form1() => InitializeComponent();
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        buttonCreateButtons.Click += onCreateButtons;
        buttonDisposeButtons.Click += onDisposeButtons;
        frm.Show(this);
        frm.Location = new Point(Right + 10, Top);
    }
    private void onCreateButtons(object? sender, EventArgs e)
    {
        for (int t = 0; t < 10; t++)
        {
            Button button = new Button
            {
                Text = $"Button {t}",
                AutoSize = true,
                Margin = new Padding(0,10,0,0),
             };
             button.Location = new Point(10, button.Margin.Top + ((button.Margin.Vertical + button.Height) * t));
             frm.Controls.Add(button);
        }
    }
    private void onDisposeButtons(object? sender, EventArgs e)
    {
        // Here is where you need an array instead of an iterator.
        foreach (var control in frm.Controls.OfType<Button>().ToArray())
        {
            control?.Dispose();
        }
    }
}

screenshots

Csharp相关问答推荐

PredicateBuilder不是循环工作,而是手动工作

如何使用C#和Graph API从Azure Directory获取用户详细信息

WPF Windows初始化正在锁定. Net 8中分离的线程

Elasticsearch:当我try 使用c#将嵌套对象添加到filter中时出现问题

Microsoft. VisualBasic. FileIO. FileSystem. MoveFile()对话框有错误?

Polly v8—使用PredicateBuilder重试特定的状态代码

如何注册接口类型,类型<>

可为空的泛型属性

S能够用DATETIME来计算,这有什么错呢?

MS Graph v5.42.0:在寻呼消息时更改页面大小

由于POST中的应用程序/JWT,出现不支持的内容类型异常

在swagger示例中添加默认数组列表

为什么@rendermode Interactive Auto不能在.NET 8.0 Blazor中运行?

数据库.Migrate在对接容器重启时失败

当try 测试具有协变返回类型的抽象属性时,类似功能引发System.ArgumentException

错误:此版本的Visual Studio无法打开以下项目

删除MudRadio时,MudRadioGroup未 Select 正确的MudRadio

C#;AvaloniaUI;MVVM;当另一个窗口上的按钮被单击时,如何更新视图图像源?

反序列化我以前使用System.Text.Json序列化的文件时出现异常

与Visual Studio 2022中的.NET框架相比,如何在.NET Core 6中获取错误输出的窗口句柄