如何获取特定类型(按钮/文本框)的 Windows 窗体窗体的所有子控件? [英] How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

查看:23
本文介绍了如何获取特定类型(按钮/文本框)的 Windows 窗体窗体的所有子控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取表单上所有类型为 x 的控件.我很确定我过去曾经看到过使用这样的代码:

I need to get all controls on a form that are of type x. I'm pretty sure I saw that code once in the past that used something like this:

dim ctrls() as Control
ctrls = Me.Controls(GetType(TextBox))

我知道我可以遍历所有使用递归函数获取子项的控件,但是有没有更简单或更直接的东西,也许像下面这样?

I know I can iterate over all controls getting children using a recursive function, but is there something easier or more straightforward, maybe like the following?

Dim Ctrls = From ctrl In Me.Controls Where ctrl.GetType Is Textbox

推荐答案

这里有另一种选择.我通过创建一个示例应用程序对其进行了测试,然后将一个 GroupBox 和一个 GroupBox 放在初始 GroupBox 中.在嵌套的 GroupBox 中,我放置了 3 个 TextBox 控件和一个按钮.这是我使用的代码(甚至包括您正在寻找的递归)

Here's another option for you. I tested it by creating a sample application, I then put a GroupBox and a GroupBox inside the initial GroupBox. Inside the nested GroupBox I put 3 TextBox controls and a button. This is the code I used (even includes the recursion you were looking for)

public IEnumerable<Control> GetAll(Control control,Type type)
{
    var controls = control.Controls.Cast<Control>();

    return controls.SelectMany(ctrl => GetAll(ctrl,type))
                              .Concat(controls)
                              .Where(c => c.GetType() == type);
}

为了在表单加载事件中对其进行测试,我想要对初始 GroupBox 内的所有控件进行计数

To test it in the form load event I wanted a count of all controls inside the initial GroupBox

private void Form1_Load(object sender, EventArgs e)
{
    var c = GetAll(this,typeof(TextBox));
    MessageBox.Show("Total Controls: " + c.Count());
}

它每次都返回正确的计数,所以我认为这非常适合您正在寻找的内容:)

And it returned the proper count each time, so I think this will work perfectly for what you're looking for :)

这篇关于如何获取特定类型(按钮/文本框)的 Windows 窗体窗体的所有子控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆