从代码隐藏中删除asp.net控件

dav*_*ooh 8 .net c# asp.net

我需要在验证某个条件时从我的页面中删除一个控件(文本框).是否有可能从代码隐藏或我需要使用JavaScript.

注意我需要删除控件,而不是隐藏...

Tim*_*ter 12

使用Controls.RemoveControls.RemoveAt在父母身上ControlCollection.

例如,如果要从页面顶部删除所有TextBox:

var allTextBoxes = Page.Controls.OfType<TextBox>().ToList();
foreach(TextBox txt in allTextBoxes)
    Page.Controls.Remove(txt);
Run Code Online (Sandbox Code Playgroud)

(请注意,您需要添加using System.LinqEnumerable.OfType)

或者如果要删除具有给定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);
Run Code Online (Sandbox Code Playgroud)

如果你只想隐藏它(并从客户端完全删除它),你也可以使它不可见:

textBox1.Visible = false;
Run Code Online (Sandbox Code Playgroud)