Question

I basically need to do the same thing as in: Get Component's Parent Form

however in compact framework there is no definition of

IDesignerHost

Any idea how to do this?

EDIT: It is System.ComponentModel.Component derived component that I want to drop on some System.Windows.Forms.Container control. The reason I need to reference to this is that I don't want to manually set Parent Container for my component in each form I will drop component to.

Was it helpful?

Solution

In the Compact Framework a Form's components are contained inside a member Container variable. There is no direct relation between that Container and the Form itself, other than the fact the Form created the instance. That instance could easily be passed to some other Form or non-Form class, for that matter, and the original parent Disposed.

What this means is that there is no way to determine the "containing Form" of a Component. That information simply isn't stored anywhere (well the GC sees the root, but that's a bit different and not queryable anyway).

Now if you only want a reference to the IContainer, and not the Form that holds the instance to the IContainer, you can query component.Site.Container, but even that's got loads of potential holes in it.

For example, if you drop a SerialPort Component onto a Form, it gets added to the components collection by the designer and serialPort.Site.Container gets set. However, if you drop a Timer Component onto a Form, the Timer is not added to the Components collections, so timer.Site is actually null, so even trying to query the Container would throw a NullReferenceException.

To make it more fun, Components like the SerialPort also have constructors that allow creation without an IContainer, so while dropping the SerialPort onto a Form in the designer will add it to a Form's Components, if a developer creates the SerialPort manually, it's pretty rare that it will get added to the Components collection at all.

Basically, I think you need to rethink your intended architecture. You'll have to come up with some mechanism that doesn't depend on the parent Container.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top