Quick tip : avoid .Parent.Parent.Parent…..

A simple way to avoid things like this :

HiddenField ct = (HiddenField)((Button)sender).Parent.Parent.Parent.Parent.Parent.Parent.Parent.FindControl("thehiddenidentifier");

is a simple loop


Control parent = ((Button)sender);
 do
 {
   parent = parent.Parent;
   ct = (HiddenField)parent.FindControl("thehiddenidentifier");
 }
 while (ct == null && parent != null);

You can make it an extension :


public static class ControlsXT
 {
 public static Control FindInParents(this Control ctrl, string searchidentifier)
 {
 Control foundControl;
 do
 {
 ctrl = ctrl.Parent;
 foundControl = ctrl.FindControl(searchidentifier);
 }
 while (foundControl == null && ctrl != null);
 return foundControl;
 }
 }

and use it this way :


HiddenField ct = null;
Control searchedControl = ((GroupRadioButton)sender).FindInParents("thehiddenidentifier");
if (searchedControl != null && searchedControl is HiddenField)
{
ct = (HiddenField)searchedControl;
}

what do you think ? do you have any other solutions ?

Incoming search terms:

  • jquery how to avoid parent parent parent