Find control recursively via extension method


/ Published in: C#
Save to your folder(s)

And usage:

protected void Page_Load(object sender, EventArgs e)

{

Label theLabel = form1.FindControlR("ControlToFind") as Label;

if (theLabel != null)

{

theLabel.Text = "Found it!";

}

}


Copy this code and paste it in your HTML
  1. public static class Extensions
  2. {
  3. /// <summary>
  4. /// Searches recursively in this control to find a control with the name specified.
  5. /// </summary>
  6. /// <param name="root">The Control in which to begin searching.</param>
  7. /// <param name="id">The ID of the control to be found.</param>
  8. /// <returns>The control if it is found or null if it is not.</returns>
  9. public static Control FindControlR(this Control root, string id)
  10. {
  11. System.Web.UI.Control controlFound;
  12. if (root != null)
  13. {
  14. controlFound = root.FindControl(id);
  15. if (controlFound != null)
  16. {
  17. return controlFound;
  18. }
  19.  
  20. foreach (Control c in root.Controls)
  21. {
  22. controlFound = c.FindControlR(id);
  23.  
  24. if (controlFound != null)
  25. {
  26. return controlFound;
  27. }
  28. }
  29. }
  30.  
  31. return null;
  32. }
  33. }

URL: http://aspadvice.com/blogs/name/archive/2008/03/31/Creating-a-Recursive-FindControl-Extension-Method.aspx

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.