Introduction
When creating your own user controls, it is often necessary to register certain events from one of your user control's parent controls. In most cases, you'd like to develop your custom user controls to be flexible enough to be used more than once, and often times by different types of parent controls. Your user control may have n number of parent controls when all is said and done. This example will allow you to recursively find a parent control of a specific type, if one exists. The control I'm going to attempt to find is a TabControl.
Using the code
The method name that will perform the recursion is called findControlParent. In your user control, you may call this method in many places; the Load event, the default constructor of your user control, or override the OnHandleCreated event. Declare a control to accept the return value back from the findControlParent method and pass in your custom user control as the only parameter using the
this
. Don't forget to include this:
using
System.Windows.Forms;
Control theTabControl = findControlParent(this);
if (theTabControl != null)
{
((TabControl)theTabControl).Selecting +=newTabControlCancelEventHandler(handler_Selecting);
}
This is the findTabControlParent method. This method takes your user control as a parameter and returns a Control. The typeof() is used to determine if the parent control is a type of control specified. In this example, I'm using the TabControl, but this could be any type of control. The method calls itself recursively if the parent control fails the typeof() test and checks the parent's parent, and so forth. This is done until the top parent node is found. The top parent node will not have a parent, so the first if statement will return null, and the control returned is set to null. In the calling method, we check for this before attempting to register the event (see code block above).
private static Control findControlParent(Control theControl)
{
Control rControl = null;
if (theControl.Parent != null)
{
if (theControl.Parent.GetType() == typeof(System.Windows.Forms.TabControl))
{
rControl = theControl.Parent;
}
else
{
rControl = findControlParent(theControl.Parent);
}
}
else
{
rControl = null;
}
return rControl;
}