This is another one of those tiny bits of code that I’ve written too many times and I don’t want to waste my time thinking about again. It’s simple, but I’m bored of writing it. I’ve also posted it to http://www.extensionmethod.net (http://www.extensionmethod.net/Details.aspx?ID=415)
Anyway it all its limited glory;
public static T FindParent(this Control target) where T : Control
{
if (target.Parent == null)
{
return null;
}
var parent = target.Parent as T;
if (parent != null)
{
return parent;
}
return target.Parent.FindParent();
}