In winforms getting a parent control of a given type

On my baseball scoring application I needed to get a parent control to share data between controls.

Because controls can have several levels between them it takes some recursion to get to the needed control.

The following generic method will get the first control of a given type.

public static T GetParent<T>(this Control ctl) where T : Control {
  var retVal = default(T);
  var parent = ctl;
  while (parent.Parent != null) {
    parent = parent.Parent;
    if (parent is T) {
      retVal = (T)parent;
      break;
    }
  }
  return retVal;
}

Comments are closed.