c# - 如何从 C# 面板控件中 Dispose() 特定用户控件?

标签 c# winforms user-controls dispose

我想从面板中处理特定类型的用户控件。现在我正在使用 foreach 循环来处理用户控件。

foreach (CTRL.box bx in RightPanel.Controls.OfType<CTRL.box>())
{
     bx.Dispose();
}

但它无法正常工作。在检查谷歌时我发现了下面的代码。

while(tabControlToClear.Controls.Count > 0)
{ 
var tabPage = tabControlToClear.Controls[0];
tabControlToClear.Controls.RemoveAt(0);
tabPage.Dispose(); 

// Clear out events.

foreach (EventHandler subscriber in tabPage.Click.GetInvocationList())
{
    tabPage.Click -= subscriber;
}
}

我正在尝试这样做,但对我来说,这是我需要处理的特定用户控件。它们是我的表单中应该需要的其他用户控件。总的来说,我想从我的表单中处理 box 用户控件。

while (RightPanel.Controls.OfType<CTRL.box>().Count() > 0)
{
      var panel = RightPanel.Controls.OfType<CTRL.box>()[0];//Here i am getting error "Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<Project_Server.CTRL.box>'"
}

谁能帮我解决这个错误。

最佳答案

错误非常明显,您无法在 IEnumerable 上应用索引

我建议使用 FirstFirstOrDefault 扩展方法来检索第一个元素并将其删除。

var panel = RightPanel.Controls.OfType<CTRL.box>().FirstOrDefault();
if(panel != null) 
{
    //logic
}

如果您想删除 CTRL.box 类型的所有控件,请使用此选项。

List<Control> controls= RightPanel.Controls.OfType<CTRL.box>().ToList();

foreach(Control c in controls)
{
    RightPanel.Controls.Remove(c);
    c.Dispose();
}

关于c# - 如何从 C# 面板控件中 Dispose() 特定用户控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42129950/

相关文章:

c# - WPF ComboBox 在初始加载时绑定(bind)到对象

winforms - 获取 parent 姓名

c# - Windows 窗体应用程序异常

c# - WPF UserControl - Usercontrol DataGrid 的 SelectedItem 绑定(bind)到 UserControl 外的 DataGrid 的 ItemSource

wpf - 如何将复选框列表的选择绑定(bind)到数据库 WPF MVVM EF

c# - 不同的类型转换行为

c# - 是否可以从 C# 中的对象修改或删除匿名类型?

c# - .NET 进程间 "events"

c# - 无需单独的项目即可获得 WinForm 的快捷方式

c# - 如何避免带有圆角的可缩放用户控件的彩色边框的视觉伪影?