Adnan Yaseen Adnan Yaseen - 25 days ago 12
ASP.NET (C#) Question

Recursively find dynamically created controls inside panel

I know that similar questions have been asked but unfortunately none of them answer my question. These answers either are working with defined number of child controls or are telling to get any specific type of control like checkbox or dropdown.

I have a page which dynamically select values from the database and render controls on the page. Now these controls could be textbox, checkbox, dropdown, listbox, radiobuttons or checkboxes or all. I have been generating different divs for different controls. So textbox control will be nested inside one parent div and the checkbox can be nested within a div which is inside another divs. So the number of parent div is different for each control. Now I want to get the controls which are generated from another function on postback.

I have been thinking to store all the types and names of all controls at the time of rendering in some dictionary object. Or the other way is to loop through controls inside panel. But how I could loop through controls when I don't know the child control will be present at which level. Isn't there are way through which I could select only Wb.UI.Controls and not other Generic Html controls?

This piece of code is not working in my case as it is only limited to two levels, (I am seeking for a way to loop without defining any child control search explicitly.

foreach (Control c in panel.Controls)
{
foreach (Control child in c.Controls)
{
if (child is TextBox)
{

}
}
}

Answer

The answer is in your question, you have to use recursion.

private void FindMyControls(ControlCollection controls)
{
    foreach (Control control in controls)
    {
        if (control is TextBox)
        {
        }
        else if (control is Checkbox)
        {
        }
        else if (control.Controls.Count > 0)
        {
            FindMyControls(control.Controls);
        }
    }
}

Add additional else if constructs to handle the different types if you need to do something different with each type. If you're just trying to get a collection of every control on the page you could simplify the above code a bit.

private void FindMyControls(ControlCollection controls)
{
    foreach (Control control in controls)
    {
        if (control.Controls.Count > 0)
        {
            FindMyControls(c.Controls);
        }
        else
        {
            // it's a control without children of its own so
            // do something with it
        }
    }
}
Comments