Sponsored Ad

Thursday, April 22, 2010

How to Find Control by Given Type in C#

 

This small utility will help you to find a control by given type from a ControlCollection. This utility will loop through all the controls in collection recursively and return the control if find any otherwise it will return null value.

using System.Web.UI;

private static Control FindControlByType(ControlCollection C, Type mytype)
      {
          Control gr = null;
          for (int i = 0; i < C.Count; i++)
          {
              System.Type t = C[i].GetType();

              if (t == mytype || t.IsSubclassOf(mytype)) gr = C[i];
              else
                  if (C[i].HasControls()) gr = FindControlByType(C[i].Controls, mytype);
              if (gr != null) break;
          }
          return gr;
      }

No comments:

Post a Comment

Sponsored Ad

Development Updates