Getting a lits of all child controls of a control, by type

纵然是瞬间 提交于 2019-12-01 11:07:14

Try this

    public static IEnumerable<Control> GetAllControls(Control parent)
    {
        foreach (Control control in parent.Controls)
        {
            yield return control;
            foreach (Control descendant in GetAllControls(control))
            {
                yield return descendant;
            }
        }
    }

and call

List<Control> ControlsToCheck = GetAllControls(dv).OfType<Label>().ToList();
Doozer Blake

When you are iterating through dv.Controls, it's only showing controls at the first level underneath your DetalsView. You need to iterate through all the child controls, and then their children, etc. if you need to find all the Labels.

The answer by @Bala R. is a great example of this. You can also find some examples on this answer.

I modified Bala R's solution a little. I made it a generic extension method that only yeilds the type of control you are interested in so you don't need to call .OfType<T> as a second step:

public static IEnumerable<T> GetControls<T>(this Control parent) where T : Control
{
    foreach (Control control in parent.Controls)
    {
        if (control is T) yield return control as T;
        foreach (Control descendant in GetControls<T>(control))
        {
            if (control is T)
                yield return descendant as T;
        }
    }
}

Used like this:

List<Label> labels = dv.GetControls<Label>().ToList();

or

foreach(Label label in dv.GetControls<Label>())
{
    //do stuff
}

this link helped me, i hope be befit 4 u2 ;)

http://msdn.microsoft.com/en-us/library/yt340bh4%28v=vs.100%29.aspx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!