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...
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With