2010-02-05 13 views
8

C#manera fácil de usar FindControl ("")

Hola,

he estado desarrollando aplicaciones web C# para un par de años y hay una cuestión Sigo upagainst que no puedo encuentra una forma lógica de resolverlo

Tengo un control al que deseo acceder en el código subyacente, este control está dentro del marcado; alojado dentro de ContentPlaceHolders, UpdatePanels, Paneles, GridViews, EmptyDataTemplates, TableCells (o cualquier estructura que desee), el punto es que tiene más padres que parientes para la justicia.

¿Cómo puedo utilizar FindControl("") acceder a este control sin hacer esto:

Page.Form.Controls[1].Controls[1].Controls[4].Controls[1].Controls[13].Controls[1].Controls[0].Controls[0].Controls[4].FindControl(""); 

Respuesta

12

Escribir un método de ayuda llamada FindControlRecursive conforme a lo dispuesto por el propio Jeff Atwood.

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; 
} 

http://www.codinghorror.com/blog/archives/000307.html

+0

+1 tarea perfecta para la recursividad –

+0

Solo un comentario a tener cuidado con el impacto en el rendimiento si abusas de la recursividad Definitivamente sigue siendo un +1. –

+0

Saludos, solo el truco :) – WillDud

3

uso recursivo 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; 
    } 
0

O en LINQ:

 private Control FindControlRecursive(Control root, string id) 
     { 
      return root.ID == id 
         ? root 
         : (root.Controls.Cast<Control>() 
          .Select(c => FindControlRecursive(c, id))) 
          .FirstOrDefault(t => t != null); 
     } 
Cuestiones relacionadas