简体   繁体   中英

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

Try this:

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

Why not use a ASP.Net skin page to set the default values for all RadioButtonLists to visible = false.

I would def look into using a skin page here.

Doing a foreach on the Controls property and checking the type is going to be slow. What you should be doing, in my opinion and depending on your requirements, is using CSS / skins to hide the unwanted buttons or simply adding them to a List<T> so you can loop through only those that you need to modify.

Worst case scenario the foreach will work but it's a bit slow and undesirable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM