查找类型的 WebForms 父控件

Find WebForms Parent Control of Type

我想查找特定类型的父控件,但不知道它的ID。

页面可能如下所示:

- MasterPage
    - HomePage
        - SomeControl
            - TargetControl
                - SomeOtherControl
                    - ThisControl

我想获得类型为 TargetControlThisControl 父级:

Control targetControl = thisControl.FindParentControl(typeof(TargetControl));

使用扩展方法很容易,递归地检查父控件类型。

public static Control FindParentControl(this Control control, Type parentType)
{
    while(control != null)
        if (control.Parent.GetType() == parentType)
            return control.Parent;
        else
            control = control.Parent;

    return null;
}