如何获得特定类型(按钮/文本框)的Windows窗体形式的所有子控件? [英] How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?
问题描述
我需要是X类型的窗体上的所有控件。我是pretty肯定,我看到了code一旦所使用这样的事情在过去的:
暗淡ctrls监视()作为控制
ctrls监视= Me.Controls(的GetType(文本框))
我知道我可以遍历获得使用递归函数的孩子所有的控制,但
是有什么更容易或更直白,也许像下面这样?
暗淡ctrls监视=从CTRL在Me.Controls凡ctrl.GetType是文本框
下面是给你另一种选择。我通过创建一个示例应用程序测试了它,然后我把一个分组框和初始分组框内部的分组框。内部嵌套分组框,我把3 TextBox控件和一个按钮。这是code我用(甚至还包括你要找的递归)
公开的IEnumerable<控制> GETALL(调节控制,型型)
{
无功控制= control.Controls.Cast<控制>(); 返回controls.SelectMany(CTRL => GETALL(CTRL,类型))
.Concat(对照)
。凡(C => c.GetType()==型);
}
要在我想最初的分组框内部的所有控制的计数的形式加载事件进行测试
私人无效Form1_Load的(对象发件人,EventArgs的发送)
{
变种C = GETALL(此的typeof(文本框));
的MessageBox.show(总控制:+ c.Count());
}
和它每次返回正确的算的,所以我认为这将很好地工作为你在找什么:)
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
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);
}
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屋!