davioooh
davioooh

Reputation: 24666

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.

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

Upvotes: 8

Views: 22208

Answers (5)

Tim Schmelter
Tim Schmelter

Reputation: 460018

Use Controls.Remove or Controls.RemoveAt on the parent ControlCollection.

For example, if you want to remove all TextBoxes from the page's top:

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 a TextBox with a 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 remove it from clientside completely), you can also make it invisible:

textBox1.Visible = false;

Upvotes: 13

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

You can try with 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

Upvotes: 0

Ramesh
Ramesh

Reputation: 13266

When you set .Visible=false, it will never be rendered in the page. 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.

Adding or removing control dynamically may result in problems.

Upvotes: 2

jrummell
jrummell

Reputation: 43067

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.

Upvotes: 3

Justin Harvey
Justin Harvey

Reputation: 14672

Yes, you can just remove it from the controles collection of the page:

this.Controls.Remove(control);

Upvotes: 1

Related Questions