Thursday, May 14, 2009

Bugged by FindControl….


I’ve always been bugged by the “FindControl” method on the Gridview, or any part of the page (I mainly use it on a gridviewrow after selecting).  So I wrote a little Generic method.  This can be added to a utilties class, or just on the codebehind page itself:


   1: public T FindControl<T>(Control searchControl, string controlId) where T : Control {

   2:         return (T)(searchControl.FindControl(controlId));        

   3:     }

To use the new FindControl:

   1: Label foo = FindControl<Label>(gvTest.SelectedRow, "myIDLabel");

This is instead of doing something like:

((gvTest.SelectedRow).FindControl("customerId") as Label).Text

Well, at least it seems cleaner to me in code.  I’m sure that there are better ways, but this works for me for now.

No comments: