我试图在 Page_Load 上隐藏我所有的 RadioButtonLists 但我似乎无法完全正确地使用语法
我猜我必须使用FindControl
类似这样的语法
CType(FindControl, RadioButtonList)
然后我猜我将不得不遍历每个 RadioButtonList 并Visible = False
在其上设置属性。
我似乎在上面的代码中遇到了错误。
有什么想法我可以尝试吗?
谢谢
我试图在 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 仅在您知道要查找的控件的名称时才有效,而且它不是递归调用。除非您可以保证您的控件将在您正在搜索的特定容器中,否则您将找不到它。如果要查找所有单选按钮列表,则需要编写一个方法,循环遍历父/子关系中的所有控件集,并将单选按钮列表设置为 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 / 皮肤来隐藏不需要的按钮,或者只是将它们添加到 a 中List<T>
,这样您就可以只遍历那些您需要修改的按钮。
在最坏的情况下,foreach 将起作用,但它有点慢且不可取。