Remove asp.net control from code

I need to remove a control (text box) from my page when a certain condition is checked. Is it possible to do this from code or do I need to use JavaScript.

NOTE I need to remove the control, not hide ...

+7
source share
5 answers

Use Controls.Remove or Controls.RemoveAt parent ControlCollection .

For example, if you want to remove all text fields from the page at the top of the page:

 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 )

or if you want to remove the TextBox with the given ID:

 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 completely remove it from the client), you can also make it invisible:

 textBox1.Visible = false; 
+11
source

While you can remove it from the control collection, why not hide it?

 yourTextBox.Visible = false; 

This will prevent it from being included in the generated html sent to the browser.

+2
source

When you set .Visible=false , it will never be displayed on the page. If you remove a control from the Controls collection, do not do this in the DataBind , Init , Load , PreRender or Unload , as it will throw an exception.

Adding or removing controls dynamically can cause problems.

+1
source

Yes, you can simply remove it from the controles collection on the page:

 this.Controls.Remove(control); 
0
source

You can try using this code - based on Remove method

 this.Controls.Remove(YourControl); 

Link: http://msdn.microsoft.com/en-US/library/system.web.ui.controlcollection.remove(v=vs.80).aspx

0
source

All Articles