[英]Javascript to loop through all asp:Hyperlink controls on a page, and hide them
[英]ASP.NET find all Controls on a page and hide them
我正试图在Page_Load上隐藏我所有的RadioButtonLists,但我似乎无法使语法完全正确
我猜我必须使用像这样的FindControl
语法
CType(FindControl, RadioButtonList)
然后我猜我将不得不遍历每个RadioButtonList并在其上设置Visible = False
属性。
我似乎在上面的代码中出错了。
我有什么想法可以尝试吗?
谢谢
尝试这个:
protected void Page_Load(object sender, EventArgs e)
{
HideRadioButtonLists(Page.Controls);
}
private void HideRadioButtonLists(ControlCollection controls)
{
foreach (WebControl control in controls.OfType<WebControl>())
{
if (control is RadioButtonList)
control.Visible = false;
else if (control.HasControls())
HideRadioButtonLists(control.Controls);
}
}
FindControl仅在您知道要查找的控件的名称时才有效,而且不仅仅是递归调用。 除非您可以保证您的控件将位于您正在搜索的特定容器中,否则您将无法找到它。 如果要查找所有radiobutton列表,则需要编写一个循环遍历父/子关系中所有控件集的方法,并将radiobuttonlist设置为false。
只需将Page.Controls
传递给此函数(未经测试,可能需要调整):
public void HideRadioButtonLists(System.Web.UI.ControlCollection controls)
{
foreach(Control ctrl in controls)
{
if(ctrl.Controls.Count > 0) HideRadioButtonLists(ctrl.Controls);
if("RadioButtonList".Equals(ctrl.GetType().Name, StringComparison.OrdinalIgnoreCase))
((RadioButtonList)ctrl).Visible = false;
}
}
为什么不使用ASP.Net皮肤页面将所有RadioButtonLists的默认值设置为visible = false。
我会在这里使用皮肤页面。
在Controls属性上执行foreach并检查类型将变慢。 在我看来,根据您的要求,您应该做的是使用CSS /皮肤隐藏不需要的按钮,或者只是将它们添加到List<T>
这样您就可以只遍历需要修改的按钮。
最糟糕的情况是foreach会起作用,但它有点慢而且不受欢迎。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.