Getting the form that hosts a control

  • Thread starter Thread starter Mystery Man
  • Start date Start date
M

Mystery Man

I have developed a series of user defined controls. These have been
placed on a variety of different forms.

From within one of these controls, I want to show another dialog
directly to the right of the current form (that contains one of this
particular control).

Therefore, what I am after is the position of the form that hosts a
control from the control itself. I realise that I can do the
following:

this.Parent.Parent...Location;

However, as this control is on a variety of forms, there is no
guarantee how many parents objects I need to retrieve in order to get
to the parent form.

Is there a way to work out which parent is the form itself or is there
a better way of doing this?
 
Hi,

You may like to traverse the hierarchy, until you find a parent
that is of type System.Windows.Forms.Form.

// 'this' refers to the user control here
Control ctrl = this;
while(ctrl.GetType() != typeof(System.Windows.Forms.Form))
{
ctrl = ctrl.Parent;
}

if(ctrl != this)
{
// Found the host form
MyForm form = (MyForm)ctrl;

}

Regards,
Aravind C
 
UserControl has a ParentForm property that is ideal for this situation.
UserControl is derived from ContainerControl, so you'll find the definition
under "ContainerControl.ParentForm Property".

Chris R.
 
Back
Top