我需要在一个表单上获得x类型的所有控件.我很确定我以前见过这样的代码:
dim ctrls() as Control
ctrls = Me.Controls(GetType(TextBox))
我知道我可以使用递归函数迭代所有控件来生成子控件,但是
Dim Ctrls = From ctrl In Me.Controls Where ctrl.GetType Is Textbox
我需要在一个表单上获得x类型的所有控件.我很确定我以前见过这样的代码:
dim ctrls() as Control
ctrls = Me.Controls(GetType(TextBox))
我知道我可以使用递归函数迭代所有控件来生成子控件,但是
Dim Ctrls = From ctrl In Me.Controls Where ctrl.GetType Is Textbox
这是你的另一个 Select .我通过创建示例应用程序对其进行了测试,然后将GroupBox和GroupBox放入初始GroupBox中.在嵌套的GroupBox中,我放置了3个TextBox控件和一个按钮.这就是我使用的代码(甚至包括您正在寻找的递归)
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);
}
要在Form Load事件中测试它,我需要初始GroupBox中所有控件的计数
private void Form1_Load(object sender, EventArgs e)
{
var c = GetAll(this,typeof(TextBox));
MessageBox.Show("Total Controls: " + c.Count());
}
每次它都会返回正确的计数,所以我认为这将非常适合您所寻找的:)