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

How to Dispose() a specific User control from panel control in C#?(如何从 C# 中的面板控件 Dispose() 特定的用户控件?)
本文介绍了如何从 C# 中的面板控件 Dispose() 特定的用户控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to dispose a specific type of User control from panel. Right now i am using foreach loop to dispose the User control.

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

但它不能正常工作.在谷歌中检查时,我找到了以下代码.

But it is not working properly. while checking in google i find the below code.

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 用户控件.

I am trying to do this, But for me it is a specific User control i need to dispose. they are other User controls which should be required in my form. Overall i want to dispose box User control from my form.

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>'"
}

谁能帮我解决这个错误.

Can anyone help me to fix this error.

推荐答案

错误很明显,你不能在 IEnumerable

Error is pretty clear, you cannot apply indexing on IEnumerable

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

I would suggest use First or FirstOrDefault extension method to retrieve first element and delete it.

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

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

In case, if you would like to remove all controls of type CTRL.box use this.

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

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

这篇关于如何从 C# 中的面板控件 Dispose() 特定的用户控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)