Who's your daddy? (control.parent null in constructor?)

  • Thread starter Thread starter Jim Margarit
  • Start date Start date
J

Jim Margarit

I'm trying to write my first windows control, subclassed from Panel.

In the constructor I try to use the parent property but it is undefined
(null). Is there any way to get to the parent in the constructor? I want
to know the dimensions of the parent container. Thanks

Jim Margarit
 
If you need the get the parent dimensions, and simply using the Dock and
Anchor properties of the subclass will not suffice, then you can override
the OnParentChanged method. When the control is first being created
(constructor) it does not yet have a parent.
 
Unless your control takes the parent as a parameter to the constructor,
there would be no way to know the parent.
When you create an instance of the control, it is not associated with
any other controls until you specifically add it to them.
You might want to create a method like this on your control:

public void AssignToParent(Control parent){
this.Parent = parent;
// do stuff that references the parents dimensions
}

Then you can do something like:

Panel mainPanel = new Panel();
....
MyControl x = new MyControl();
x.AssignToParent(mainPanel);
 
Just to add to what the others have said, if you look in the
InitializeComponent method of the parent form, the form must first create an
instance of your control before it can add it to its Control collection,
hence no parent until the forms constructor has finished running.

HTH
Dan
 
Thanks to all. OnParentChange should do the trick. So many similarities
to Delphi, so many differences...

Jim
 
Back
Top