C# 使 UserControl 删除自身
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/699410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make UserControl remove itself
提问by Brian Sweeney
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.
this
是一个扩展用户控制的类。当我逐步完成这部分代码时,看起来一切都很好,但是表单没有任何反应。我希望控制消失。
采纳答案by Mark Brackett
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);
.
如前所述,您正在从自身中删除控制权……这不太可能是您想要的。我假设你想从它的父级中删除控件- 所以你可能想要this.Parent.Controls.Remove(this);
.
Luckily, since you didn't mention platform, the code is the same for WebFormsor WinForms.
回答by womp
this.Controls is the collection of Controls existing within your usercontrol. "this" would not exist inside that collection, as "this" is the parent.
this.Controls 是存在于用户控件中的控件的集合。“this”不会存在于该集合中,因为“this”是父级。
I think you want to find the form object, and do myForm.Controls.Remove(this).
我想你想找到表单对象,然后做 myForm.Controls.Remove(this)。
回答by Neil N
Nothing happens because it doesnt find 'this' in the controls collection of 'this'
什么也没发生,因为它在“this”的控件集合中找不到“this”
If your scope is within the Control itself, you would want to do
如果您的范围在 Control 本身内,您会想要做
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 替换为已知的容器类型(即面板)
((Form)this.Container).Controls.Remove(this);
回答by Ken Browning
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.
但是,我要指出的是,从页面中删除自身的控件并不是我认为的任何 asp.net 控件的“预期行为”。覆盖该Render
方法(或将Visible
属性设置为false
)将产生相同的结果,并且不会让将来维护该代码的人感到困惑。