Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make UserControl remove itself

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.

like image 987
Brian Sweeney Avatar asked Jun 30 '26 23:06

Brian Sweeney


2 Answers

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.

like image 99
Mark Brackett Avatar answered Jul 03 '26 11:07

Mark Brackett


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);
like image 35
Neil N Avatar answered Jul 03 '26 11:07

Neil N