查找类型的WebForms父控件

时间:2019-02-14 18:37:49

标签: webforms controls

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

页面看起来像这样:

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

我想获得ThisControl类型的TargetControl父对象:

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

1 个答案:

答案 0 :(得分:0)

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

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;
}
相关问题