views:

304

answers:

5

Does anyone see anything wrong with this:

this.Controls.Remove(this);

this is a class which extends user control. When I step through this section of code it looks like everything is fine, however nothing happens to the form. I would expect the control to be gone.

Thanks,

brian

+1  A: 

this.Controls is the collection of Controls existing within your usercontrol. "this" would not exist inside that collection, as "this" is the parent.

I think you want to find the form object, and do myForm.Controls.Remove(this).

womp
+3  A: 

Nothing happens because it doesnt find 'this' in the controls collection of 'this'

If your scope is within the Control itself, you would want to do

this.Container.Controls.Remove(this);

but it all depends on what type of control and in what type of container. but the above should work in most cases.

EDIT:

If you know your control belongs to a form, you can do the following, or replace Form with the known container type (i.e. a panel)

((Form)this.Container).Controls.Remove(this);
Neil N
+3  A: 

Other responses are right to point out that you're not using the correct collection.

However, I will point out that a control which removes itself from the page is not what I would consider "expected behavior" from any asp.net control. Overriding the Render method (or setting the Visible property to false) would have the same result and with a lot less opportunity to confuse whoever will be maintaining that code in the future.

Ken Browning
this is the code attached to the remove button for this widget...seems like a fair place, but point taken either way
sweeney
+1  A: 

As mentioned, you're removing the control from itself...that's not likely what you want. I assume you want to remove the control from it's parent - so you probably want this.Parent.Controls.Remove(this);.

Luckily, since you didn't mention platform, the code is the same for WebForms or WinForms.

Mark Brackett
A: 

I ended up using this code:

this.Parent.Controls.Remove(this);
sweeney