Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to use FindControl("")

Tags:

c#

asp.net

C#

Hi,

I've been developing c# web applications for a couple of years and there is one issue I keep coming upagainst that I can't find a logical way to solve.

I have a control I wish to access in code behind, this control is deep within the markup; burried within ContentPlaceHolders, UpdatePanels, Panels, GridViews, EmptyDataTemplates, TableCells (or whatever structure you like.. the point is it has more parents than farthers for justice).

How can I use FindControl("") to access this control without doing this:

Page.Form.Controls[1].Controls[1].Controls[4].Controls[1].Controls[13].Controls[1].Controls[0].Controls[0].Controls[4].FindControl("");
like image 900
WillDud Avatar asked Feb 05 '10 16:02

WillDud


2 Answers

Write a helper method called FindControlRecursive as provided by Jeff Atwood himself.

private Control FindControlRecursive(Control root, string id) 
{ 
    if (root.ID == id)
    { 
        return root; 
    } 

    foreach (Control c in root.Controls) 
    { 
        Control t = FindControlRecursive(c, id); 
        if (t != null) 
        { 
            return t; 
        } 
    } 

    return null; 
} 

Recursive Page.FindControl

like image 123
Robin Day Avatar answered Oct 12 '22 15:10

Robin Day


Use Recursive FindControl:

public T FindControl<T>(string id) where T : Control
   {
       return FindControl<T>(Page, id);
   }

   public static T FindControl<T>(Control startingControl, string id) where T : Control
   {
       // this is null by default
       T found = default(T);

      int controlCount = startingControl.Controls.Count;

      if (controlCount > 0)
      {
          for (int i = 0; i < controlCount; i++)
          {
              Control activeControl = startingControl.Controls[i];
              if (activeControl is T)
              {
                 found = startingControl.Controls[i] as T;
                  if (string.Compare(id, found.ID, true) == 0) break;
                  else found = null;
              }
              else
              {
                  found = FindControl<T>(activeControl, id);
                  if (found != null) break;
              }
          }
      }
      return found;
  }  
like image 42
ozsenegal Avatar answered Oct 12 '22 16:10

ozsenegal