Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法处置控件并从控件列表中删除控件_C#_.net_Visual Studio - Fatal编程技术网

C# 无法处置控件并从控件列表中删除控件

C# 无法处置控件并从控件列表中删除控件,c#,.net,visual-studio,C#,.net,Visual Studio,谢谢你的阅读 我有一个C#.NET表单,它带有在主面板中切换控件的按钮。在升级到Visual Studio 2012和高级安装程序之前,我没有遇到任何问题。目标框架是4.0,而不是4.5 当我更改控件时,我会在添加新控件之前处理并删除上一个控件,但是当还没有任何控件时(即第一个控件加载时),我会收到一个错误 最初的循环由于修改集合时的迭代而崩溃,所以现在我尝试在确保控件存在后删除一个控件 此错误与:索引0超出范围 这一切都可以在开发人员的机器上正常工作,使用旧的内置VS安装程序也不是问题 有什么

谢谢你的阅读

我有一个C#.NET表单,它带有在主面板中切换控件的按钮。在升级到Visual Studio 2012和高级安装程序之前,我没有遇到任何问题。目标框架是4.0,而不是4.5

当我更改控件时,我会在添加新控件之前处理并删除上一个控件,但是当还没有任何控件时(即第一个控件加载时),我会收到一个错误

最初的循环由于修改集合时的迭代而崩溃,所以现在我尝试在确保控件存在后删除一个控件

此错误与:索引0超出范围

这一切都可以在开发人员的机器上正常工作,使用旧的内置VS安装程序也不是问题

有什么想法吗?4.0框架问题?未部署缺少的引用

谢谢

panelMain.SuspendLayout();
int control_count = panelMain.Controls.Count;
if (control_count > 1) {
    Log.Write("More than one control found in main panel.", ErrorLevel.Error);
}
if (control_count > 0) {
    Control current_ctrl = panelMain.Controls[0];
    current_ctrl.Dispose();
    panelMain.Controls.Remove(current_ctrl);
}

//foreach (Control ctrl in panelMain.Controls) {
//    ctrl.Dispose();
//    panelMain.Controls.Remove(ctrl);
//}

您已经注释掉的foreach循环的问题是,无法向当前正在枚举的集合添加项或从中删除项。这意味着,如果要循环遍历集合并删除项,则必须使用for循环。如果要删除多个项目,则必须向后循环

第二条if语句的问题是,处理控件会自动将其从其父控件集合中删除。这意味着,只要对控件调用Dispose,控件集合中就不再有项,因此Remove调用将失败


因此,这个故事的寓意是,您应该使用for循环,向后循环,并使用just Dispose来销毁和删除控件。

如果有人感兴趣,这里有一个简单的递归方法来处理控件。使用上述建议

注意:确保阅读了关于Visible属性的所有注释,并将其设置回true

    // Start by calling a parent control containing the controls you want to 
    // destroy such as a form, groupbox or panel
    private void DisposeControls(Control ctrl)
    {
        // Make control disappear first to avoid seeing each child control 
        // disappear. This is optional (if you use - make sure you set parent 
        // control's Visible property back to true if you create controls 
        // again)
        ctrl.Visible = false;
        for (int i = ctrl.Controls.Count - 1; i >= 0; i--)
        {
            Control innerCtrl = ctrl.Controls[i];

            if (innerCtrl.Controls.Count > 0)
            {
                // Recurse to drill down through all controls
                this.DisposeControls(innerCtrl);
            }

            innerCtrl.Dispose();
        }
    }