Wednesday, May 13, 2009

Searching Through All Controls in a ControlCollection

I had a user control at work that dynamically added TextBoxes to a HtmlTable.  After figuring out how to even access the dynamic controls, I needed to be able to retrieve them easily.  Since the ids were based on a primary key id from the database, I couldn't determine what the ids of the TextBoxes were using the FindControl() method.  I could hit the database again to find the ids and then use the FindControl method, but I didn't like having another database hit if I could help it.

What I wanted to be able to do was enumerate over all of the controls located within my user control.  After thinking about it for a bit, I decided to finally make use of the C# "yield" statement and create my own recursive iterator method:

public static IEnumerable<Control> GetAllControls(this ControlCollection controls)
{
foreach (Control control in controls)
{
yield return control;

foreach(Control childControl in control.Controls.GetAllControls()){
yield return childControl;
}
}
}

Now I could do a foreach against all controls within a ControlCollection, and process any TextBoxes:

foreach (Control control in PlaceHolder1.Controls.GetAllControls())
{
if (control.GetType() == typeof(TextBox))
{
// Do Work Here
}
}

I believe that this could be extremely useful and wonder why it wasn't included in .Net to begin with.

No comments:

Post a Comment