如何获得胜利表格的所有控件? [英] how to get all controls of win form?

查看:166
本文介绍了如何获得胜利表格的所有控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格名为 A

A 包含很多不同的控件,包括一个主分组框。这分组框包含大量的表格和其他分组框上课的。我想找到一个控制其中有例如在形式上标签指数9 A ,但我不知道是哪个分组框包含该控件。

A contains lots of different controls, including a main GroupBox. This GroupBox contains lots of tables and others GroupBoxes. I want to find a control which has e.g. tab index 9 in form A but I don't know which GroupBox contains this control.

我怎样才能做到这一点?

How can I do this?

推荐答案

通过递归...

public static IEnumerable<T> Descendants<T>( this Control control ) where T : class
{

    foreach ( Control child in control.Controls ) {

        T childOfT = child as T;
        if ( childOfT != null ) {
            yield return (T)childOfT;
        }

        if ( child.HasChildren ) {
            foreach ( T descendant in Descendants<T>( child ) ) {
                yield return descendant;
            }
        }

    }

}

您可以使用上面的函数:

You can use the above function like:

var checkBox = (from c in myForm.Descendants<CheckBox>()
                where c.TabIndex == 9
                select c).FirstOrDefault();

这会得到的第一个复选框有9.你可以明显用的TabIndex形式中的任何位置任何你想要的标准。

That will get the first CheckBox anywhere within the form that has a TabIndex of 9. You can obviously use whatever criteria you want.

修改

如果你不LINQ查询语法的粉丝,上面可以重新写为:

EDIT
If you aren't a fan of LINQ query syntax, the above could be re-written as:

var checkBox = myForm.Descendants<CheckBox>()
                     .FirstOrDefault(x=>x.TabIndex==9);

这篇关于如何获得胜利表格的所有控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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