Recently I wanted a way to recursively iterate through a control, and its children and perform a certain operation on all controls of a specific type. I did a quick search on Google for this, but surprisingly wasn’t able to come up with much. I know someone has definitely done this, but I’m going to post my solution in the meantime, in hopes that others looking for this simple type of thing, will stumble across it. I’m open to any feedback on improving it. Enjoy.
/// <summary> /// Iterates through a control, and its children of a certain type, so that we /// can perform an operation on them. /// </summary> /// <param name="aContainer">Parent Container Control</param> /// <param name="aType">Type of control to perform operation on</param> public static void IterateControlForType(Control aContainer, Type aType) { //Check to make sure control is of type if (aContainer.GetType() == aType) { //Will need to do control check here for your type if (aContainer is LinkButton) { //In this case, we use a link button, but this can be any //control you want. Make the neccessary changes, and move on LinkButton lb = aContainer as LinkButton; lb.Text = "Some Text!"; } } foreach (Control aCtrl in aContainer.Controls) { //Recursive call to method with child controls as parameter if (aCtrl != null) { IterateControlForType(aCtrl, aType); } } }
Leave A Comment