开发者

How to retrieve the parent control and its children controls - Winforms C# 2

I want to retrieve controls of a form. To do this :

internal static IEnumerable<Control> EnumereTousControle(Control controleParent)
{
    foreach (Control subControl in controleParent.Controls)
    {
        yield return subControl;

        foreach (Control c in EnumereTousControle(subControl))
            yield return c;
    }
}

It works fine, all children of the parent control开发者_StackOverflow社区 are retrieved. But I need this method returns the parent control too. I tried this but it don't works (because the method is recursive) :

internal static IEnumerable<Control> EnumereAllControls(Control parentControl)
{
    yield return parentControl; // does not work

    foreach (Control subControl in parentControl.Controls)
    {
        yield return subControl;

        foreach (Control c in EnumereAllControls(subControl))
            yield return c;
    }
}

Thanks for your help !


Thnk you just had one line too many, try this:

internal static IEnumerable<Control> EnumereAllControls(Control parentControl)
{
    yield return parentControl;

    foreach (Control subControl in parentControl.Controls)
    {
        foreach (Control c in EnumereAllControls(subControl))
            yield return c;
    }
}


    internal static IEnumerable<Control> EnumereTousControle(Control controleParent) {
        yield return controleParent;
        foreach (Control ctl in controleParent.Controls) {
            foreach (Control child in EnumereTousControle(ctl)) 
                yield return child;
        }
    }

Well, same thing minus the extra yield you got.


You could add the parent control to the result from outside the method if that is not a constraint.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜