Tag: controlcollection

使用C#以递归方式从controlcollection中获取控件集合

目前,我正在尝试从递归控件集合(转发器)中提取动态创建的控件(复选框和下拉列表)的集合。 这是我正在使用的代码。 private void GetControlList(ControlCollection controlCollection, ref List resultCollection) { foreach (Control control in controlCollection) { if (control.GetType() == typeof(T)) resultCollection.Add((T)control); if (control.HasControls()) GetControlList(controlCollection, ref resultCollection); } } 我遇到以下问题: resultCollection.Add((T)control); 我收到错误…… Cannot convert type ‘System.Web.UI.Control’ to ‘T’ 有任何想法吗?

枚举本质上不是IEnumerable的集合?

当你想递归枚举一个分层对象,根据一些标准选择一些元素时,有许多技术的例子,比如“展平”,然后使用Linq进行过滤:如下所示: 链接文字 但是,当你枚举类似Form的Controls集合或TreeView的Nodes集合时,我一直无法使用这些类型的技术,因为它们似乎需要一个参数(对于扩展方法),这是一个IEnumerable集合:传入SomeForm.Controls不编译。 我发现最有用的是: 链接文字 这为您提供了Control.ControlCollection的扩展方法,其中包含IEnumerable结果,然后您可以使用Linq。 我修改了上面的例子来解析TreeView的节点没有问题。 public static IEnumerable GetNodesRecursively(this TreeNodeCollection nodeCollection) { foreach (TreeNode theNode in nodeCollection) { yield return theNode; if (theNode.Nodes.Count > 0) { foreach (TreeNode subNode in theNode.Nodes.GetNodesRecursively()) { yield return subNode; } } } } 这是我现在使用扩展方法编写的代码: var theNodes = treeView1.Nodes.GetNodesRecursively(); var filteredNodes = ( from n in theNodes where […]