Wednesday, February 10, 2010

A generic FindControl extension method

In order to clean up and make our code more readable, generics and extension methods comes in very handy. In ASP.NET, the Control class has a FindControl method which is used as follows:

((TextBox) Page.FindControl("TxtName")).Text = "Some name";

Since this method returns a Control type, we must cast it to it's actual type before we can access any of it's members. A way to improve this code, is to create a new generic FindControl method. Since all the controls in ASP.NET such as Page, Button, TextBox, inherits from the Control class, we can make this method an extension method. By doing this, our method can be accessed the same way as the non-generic FindControl method:

Page.FindControl("TxtName").Text = "Some name";

This code is tidier and easier to read. Here is the code for the extension method:

public static class ControlExtensions
 public static T FindControl(this System.Web.UI.Control control, string id)
  where T : System.Web.UI.Control
  return (T) control.FindControl(id);