Search code examples
asp.netloopsradiobuttonlist

ASP.NET find all Controls on a page and hide them


I'm trying to on Page_Load hide all my RadioButtonLists but I can't seem to get the syntax quite right

I'm guessing I've got to use the FindControl syntax something like this

CType(FindControl, RadioButtonList)

And then I'm guessing I will have to loop through each RadioButtonList and set the Visible = False attribute on it.

I seem to be getting an error with the code above.

Any ideas what I can try?

Thanks


Solution

  • FindControl only works if you know the name of the control you're looking for, and more than that it is not a recursive call. Unless you can guarantee that your control will be in the specific container you're searching in, you won't find it. If you want to find all of the radiobutton lists, you'll need to write a method that cycles through all control sets in the parent/child relationship and sets the radiobuttonlist visible to false.

    Just pass Page.Controls to this function (untested, may need tweaking):

    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;
        }
    }