Click here to Skip to main content
13,293,950 members (54,742 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


3 bookmarked
Posted 1 Feb 2010

Finding Specific Type Parent Control in ASP.NET

, 1 Feb 2010
Rate this:
Please Sign up or sign in to vote.

While working on a page with nested DataLists, I found it difficult to find the parent DataListItems of controls nested in panels and other server side container controls. I had to repeat calling the Parent property of controls till I get the required Parent control. The repeation of calling of Parent property is error prone as any subtle change in the page structure could throw an exception. This helper method finds the parent control using extension method to the Control class of

The Code

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;
                parentCtl = parentCtl.Parent;
        return retVal;


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Haris Munawar
Software Developer
Pakistan Pakistan
This member doesn't quite have enough reputation to be able to display their biography and homepage.

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171207.1 | Last Updated 1 Feb 2010
Article Copyright 2010 by Haris Munawar
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid