ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

FindImmediateParentOfType<T>

An extension method to find the parent control of a specific type in asp.net

Source

public static T FindImmediateParentOfType<T>(this Control control) where T : Control
{
    T retVal = default(T);
    Control parentCtl = control.Parent;
    while (parentCtl != null)
    {
        if (parentCtl is T)
        {
            retVal = (T)parentCtl;
            break;
        }
        else
        {
            parentCtl = parentCtl.Parent;
        }
    }
    return retVal;
 
}

Example

TextBox tb = getTextBox();

DataList parentDataList = tb.FindImmediateParentOfType<DataList>();

Author: Haris Munawar

Submitted on: 21 jul. 2011

Language: C#

Type: System.Web.UI.Control

Views: 4480