most reliable way to get control's form on initialization?

  • Thread starter Thread starter Bob
  • Start date Start date
B

Bob

On a control's initialization I need to set a variable with events to its
containing form, but can't use OnParentChanged or OnLayout if it's parented by
another control. I could do something cheesy like do FindForm on the first
visible change, but I thought there might be a more direct, built-in way of
doing this. Is there?

TIA,
Bob
 
Bob said:
Heh heh. But what if the parent is also parented by something
other than the form?

That shouldn't be a problem, because in this case it will
register for the ParentChanged event on the parents parent.
Take your time to think it through ;)
 
FindForm only returns a form when ParentChanged is fired during initialization
for controls that have a form as their direct parent, and this applies to
control's parent's parent just as much as any other control. In addition, your
suggestion is prone to generating exceptions for when ParentChanged is fired and
the sender does not have a parent yet, which is pretty common during
initialization.

As a side note, your code was apparently not written with Option Strict On (you
assign an object to a variable of type control without CType or DirectCast, and
don't even check the type first), which is a no-no.You should also get in the
habit of using Return instead of Exit Sub and Exit Function.

Bob
 
Back
Top