tags:

views:

17

answers:

2

Hi, I have page which has many DropDownLists. I want to access them all with foreach I had found some codes but they didn't worked for me. Some of them are having page.controls etc.

I have

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI.WebControls; using System.Web.UI;

Classes also in the project..

thx

A: 

You won't be able to access them all with one foreach because they can be at different levels and branches in the control tree. You will need to start from the page level and go down recursively on all the child controls (using the Controls property) and this way you should be able to reach all of them.

CyberDude
+2  A: 

This may help:

protected List<T> GetControlsOfType<T>(Control control) where T : Control
{
    List<T> list = new List<T>();
    list.AddRange(control.Controls.OfType<T>());
    foreach (Control item in control.Controls)
    {
        list.AddRange(GetControlsOfType<T>(item));
    }
    return list;
}

You will need:

foreach(DropDownList ddl GetControlsOfType<DropDownList>(Page)){
    // Here it is.
}
Musa Hafalır
thanks Musa it worked for me =))
zapoo