views:

19

answers:

2

In my aspx page, I have a number of drop down controls.

I would like to update an attribute on each of the controls with "class=leftColumn" with the following line:

propertyID.Attributes["nameOfAttribute"] = "false";

But instead of manually writing out each controlID and setting its attribute with the line above, I had hoped there was a way to go through and set the attribute on each control ID if it had class=leftcolumn.

This is something I know is very easy with JQuery, BUT I need to do it with the code behind (C#)

I was told this is not possible (i.e. to acquire a list of all the controls and then iterate through the list and give it the attribute or any other way. That manually setting each control like the above example is the only way in ASP.NET.

Thanks,

A: 

You don't mention if the dropdowns are at least included in some common container to help finding them. If not, and you need to literally scan the entire page for any such dropdown, then I suggest creating a recursive method that starts at page level and enumerates the Controls collections of children and of children of children and so forth and analyzing each found control.

CyberDude
+2  A: 

Use LINQ for this. You can define an extension method to help. The ControlCollection needs some help. Something like:

foreach (DropDownList dd in this.Controls
                                .All()
                                .OfType<DropDownList>()
                                .Where(c => c.Attributes["foo"] == "bar"))
{ 
    // do something              
}

...

//define the extension method.
public static IEnumerable<Control> All(this ControlCollection controls)
{
    foreach (Control control in controls)
    {
        foreach (Control grandChild in control.Controls.All())
            yield return grandChild;

        yield return control;
    }
}

Kudos to David Findley at his ASP.NET blog.

p.campbell