Finding Nested Control's Parent Form?

  • Thread starter Thread starter Mario T. Lanza
  • Start date Start date
M

Mario T. Lanza

Call me a fool but I couldn't find a way to find the form that was
ultimately the parent of a control when the control itself was nested.

I one case, I created an inherited Panel class. In it I needed to make
reference to the parent form and subscribe to its events. Unfortunately
using the control.Parent property only works if the control is directly
pasted onto the form. If my panel is nested inside of other
panels/controls, this isn't so easy. As such I wrote a class called
ParentFormFinder. (below)

Unfortunately, it is rather intensive and it seems a waste of processing
power. Am I missing some easier approach?

Since I have apparently been having memory leak issues in .NET I am
beginning to investigate my designs. I am wondering if this class might be
a culprit for dangling object references (namely to the event handler).


public class ParentFormFinder
{
private Control ctrl;
private Form form;
public event System.EventHandler FoundParentForm;

public ParentFormFinder(Control ctrl)
{
this.ctrl = ctrl;
this.ctrl.ParentChanged += new System.EventHandler(this_ParentChanged);
}

public Form Form
{
get{return this.form;}
}

public void Dispose()
{
this.Dispose(true);
}

protected void Dispose(bool explicitCall)
{
this.form = null;
this.ctrl = null;
}

private void OnFoundParentForm(object sender, System.EventArgs e)
{
if (this.FoundParentForm != null)
this.FoundParentForm(sender, e);
}

private void this_ParentChanged(object sender, System.EventArgs e)
{
Control ctrl = (Control)sender;
do
{
if (ctrl.Parent is Form)
{
this.form = (Form)ctrl.Parent;
this.OnFoundParentForm(this.form, e);
return;
}
else
{
if (ctrl.Parent == null)
{
ctrl.ParentChanged += new System.EventHandler(this_ParentChanged);
return;
}
else
ctrl = ctrl.Parent;
}
}while (true);
}
}

Mario T. Lanza
Clarity Information Architecture, Inc.
 
* "Mario T. Lanza said:
Call me a fool but I couldn't find a way to find the form that was
ultimately the parent of a control when the control itself was nested.

Why not use the control's 'FindForm' method to do that?
 
Why not use the control's 'FindForm' method to do that?

That's just the simple answer I was looking for!!

Thanks.
 
Back
Top