Thursday, December 16, 2010

Control.Find<T>(string id) Extension Method

For my current project, I am constantly using FindControl to dynamically locate a child control within a parent control. Instead of constantly typing this:

   1: DropDownList dropDownList = employeeListView.FindControl("regionDropDownList") as DropDownList;

I created an extention method to prettify my code:

   1: public static class ControlExtensions
   2: {
   3:     public static T Find<T>(this Control control, string id) where T : Control
   4:     {
   5:         return (T) control.FindControl(id);
   6:     }
   7: }

So now I can type this:

   1: employeeListView.Find<DropDownList>("regionDropDownList");


No comments:

Post a Comment