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