Click here to Skip to main content
15,888,293 members
Articles / Web Development / ASP.NET
Tip/Trick

Finding Specific Type Parent Control in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.33/5 (2 votes)
1 Feb 2010CPOL 16.5K   3  
Introduction...
Introduction

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 asp.net.

The Code

C#
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;

    }

License

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


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

Comments and Discussions

 
-- There are no messages in this forum --