Orphaned custom controls

L

Laurence Reeves

Wall, up, driven I have been.

I runtime "Controls.Add" eighteen of my custom controls (two varieties).

A seemingly random (but consistent) eleven of them instantly lose their
parentange.

I do virually anything, and the remaining magnificent seven of them drop
off the face of the form.

I don't think I'm doing anything particularly wierd. I've tried them
deriven from System.Windows.Forms.Control and ditto,UserControl (which I
don't want, 'cos I'm using Region to make irregular shaped controls).

My controls work fine at design time, and ones added then persist later
on. It's just the runtime added ones that fade into oblivion. They're
still present as objects - all they seem to have lost is their parentage.

I'm using #Develop, XP, if that makes the slightest difference.
 
A

Anders Borum

Let's see some code. Make sure you're instiating a new object, then add it
to the parent controls collection. Adding the same control to a set of
different parent controls won't "copy" the object.

I'm sure you're aware of this, but I just wanted to point it out!
 
L

Laurence Reeves

Anders said:
Let's see some code. Make sure you're instiating a new object, then add it
to the parent controls collection. Adding the same control to a set of
different parent controls won't "copy" the object.

I'm sure you're aware of this, but I just wanted to point it out!

Thanks for the comments, I was doing all that part fine. I had trouble
trying to come up with any *short* bit of code that exhibited the
behaviour. To cut to the answer (which is purely newbie):

I had (erroneously) latched onto "using (expression)" as a means of
typecasting - not a good idea!

using (Control C = (Control)thing.Tag) { C.Visible = true; etc... }

That makes the control visible, but then instantly disposes of it.

Trivially, I know that I should have said:

{ Control C = (Control)thing.Tag; C.Visible = true; etc... }

(it's shorter, even! :p) duhhh )

I feel sure there ought to be some kind of error reported - rather than
the horrible side effect it was cauasing.

Is there really any use for my stupid sort of construct - given that the
compiler can see that I haven't brought a new object into existence in
the "using ()", so I'm hardly likely to want to throw anything away
(maybe it should be called the "un-using (expression)" statement! From
the SDK docs: "You *create* an instance in a using statement ..." - but
I didn't, so it's an error.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top