Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an asp.net control from code-behind

Tags:

c#

.net

asp.net

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...

like image 448
davioooh Avatar asked Oct 09 '12 14:10

davioooh


1 Answers

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;
like image 139
Tim Schmelter Avatar answered Oct 23 '22 02:10

Tim Schmelter