我正试图在Page_Load上隐藏我的所有RadioButtonLists,但我似乎无法使语法正确
我猜我必须使用类似这样的FindControl
语法
CType(FindControl, RadioButtonList)
然后我猜我将不得不遍历每个RadioButtonList并在其上设置Visible = False
属性。
我似乎在上面的代码中出错。
我能尝试什么想法?
谢谢
答案 0 :(得分:3)
试试这个:
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);
}
}
答案 1 :(得分:1)
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;
}
}
答案 2 :(得分:0)
为什么不使用ASP.Net皮肤页面将所有RadioButtonLists的默认值设置为visible = false。
我会在这里使用皮肤页面。
答案 3 :(得分:0)
在Controls属性上执行foreach并检查类型将变慢。在我看来,根据您的要求,您应该做的是使用CSS /皮肤隐藏不需要的按钮,或者只是将它们添加到List<T>
,这样您就可以只遍历那些需要修改的按钮。 / p>
最糟糕的情况是foreach会起作用,但它有点慢且不受欢迎。