[英]Remove an asp.net control from code-behind
I need to remove a control (a textbox) from my page when a certain condition is verified. 我需要在验证某个条件时从我的页面中删除一个控件(文本框)。 Is it possible to do from code-behind or I need to use JavaScript.
是否有可能从代码隐藏或我需要使用JavaScript。
NOTE I need to remove the control, not to hide... 注意我需要删除控件,而不是隐藏...
Use Controls.Remove
or Controls.RemoveAt
on the parent ControlCollection
. 在父
ControlCollection
上使用Controls.Remove
或Controls.RemoveAt
。
For example, if you want to remove all TextBoxes from the page's top: 例如,如果要从页面顶部删除所有TextBox:
var allTextBoxes = Page.Controls.OfType<TextBox>().ToList();
foreach(TextBox txt in allTextBoxes)
Page.Controls.Remove(txt);
(note that you need to add using System.Linq
for Enumerable.OfType
) (请注意,您需要
using System.Linq
为Enumerable.OfType
添加)
or if you want to remove a TextBox with a given ID: 或者如果要删除具有给定ID的TextBox:
TextBox textBox1 = (TextBox)Page.FindControl("TextBox1"); // note that this doesn't work when you use MasterPages
if(textBox1 != null)
Page.Controls.Remove(textBox1);
If you just want to hide it (and remove it from clientside completely), you can also make it invisible: 如果你只想隐藏它(并从客户端完全删除它),你也可以使它不可见:
textBox1.Visible = false;
While you could remove it from the controls collection, why not hide it instead? 虽然您可以从控件集合中删除它,但为什么不隐藏它呢?
yourTextBox.Visible = false;
This will prevent it from being included in the generated html sent to the browser. 这将阻止它被包含在发送到浏览器的生成的html中。
When you set .Visible=false
, it will never be rendered in the page. 设置
.Visible=false
,它将永远不会在页面中呈现。 If you remove the control from Controls collection, don't do it during DataBind
, Init
, Load
, PreRender
or Unload
phases as it will throw exception. 如果从Controls集合中删除控件,请不要在
DataBind
, Init
, Load
, PreRender
或Unload
阶段执行此操作,因为它会引发异常。
Adding or removing control dynamically may result in problems. 动态添加或删除控件可能会导致问题。
是的,您可以从页面的controles集合中删除它:
this.Controls.Remove(control);
You can try with this code - based on Remove method
您可以尝试使用此代码 - 基于
Remove method
this.Controls.Remove(YourControl);
Link : http://msdn.microsoft.com/en-US/library/system.web.ui.controlcollection.remove(v=vs.80).aspx 链接: http : //msdn.microsoft.com/en-US/library/system.web.ui.controlcollection.remove(v=vs.80).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.