Web Design that taps into the haromny and vision of your dreams.

Using C# to Recursively Call FindControl in ASP.Net

Recursive FindControl in ASP.Net

Written By on in C#

71 words, estimated reading time 1 minutes.

In ASP.Net I often need to use the recursively use FindControl to get an object reference to a control on the ASPX page. The only problem with this is that you need to know the control that it is contained with. This recursive method will search for a given control within a parent control and all it's child controls.

public static Control FindControlRecursive(Control container, string name)
{
    if ((container.ID != null) && (container.ID.Equals(name)))
        return container;
 
    foreach (Control ctrl in container.Controls)
    {
        Control foundCtrl = FindControlRecursive(ctrl, name);
        if (foundCtrl != null)
            return foundCtrl;
    }
    return null;
}

Usage

You need to pass in two parameters, a reference to a control to look in and the name of the control to find.

Example:

Control myControl = FindControlRecursive(PlaceHolder1, "myControl");

Last updated on: Wednesday 21st June 2017

 

Comments
Tigrou

Tigrou

@roy : your function is nice but return type should be T instead of Control, otherwise using templates is pretty useless....

private T GetControl<T>(Control Container, string ControlID) where T : Control

Reply to Tigrou
Roy

Roy

Good post. This is the one we use.

<code>
private Control GetControl<T>(Control Container, string ControlID) where T : Control
{
T result = Container.FindControl(ControlID) as T;

if (result == null)
{
foreach (Control c in Container.Controls)
{
result = this.GetControl<T>(c, ControlID) as T;

if (result != null)
{
break;
}
}
}

return result;
}
</code>

Reply to Roy

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me