2011-09-13 3 views
1

동적으로 생성 된 컨트롤 (즉, 동적 컨트롤의 하위)에 대해 특정 중첩 컨트롤을 어떻게 구합니까? 필자가 믿는 TopLevel 동적 컨트롤 만 처리하기 때문에 FindControl() 메서드가 작동하지 않습니다. (C# 코드)를PostBack의 동적 중첩 컨트롤에 대한 FindControl() 메서드

public static Control FindControl(Control parentControl, string fieldName) 
    { 
     if (parentControl != null && parentControl.HasControls()) 
     { 
      Control c = parentControl.FindControl(fieldName); 
      if (c != null) 
      { 
       return c; 
      } 

      // if arrived here, then not found on this level, so search deeper 

      // loop through collection 
      foreach (Control ctrl in parentControl.Controls) 
      { 
       // any child controls? 
       if (ctrl.HasControls()) 
       { 
        // try and find there 
        Control c2 = FindControl(ctrl, fieldName); 
        if (c2 != null) 
        { 
         return c2; // found it! 
        } 
       } 
      } 
     } 

     return null; // found nothing (in this branch) 
    } 

답변

3

당신은 당신의 컨트롤을 통해 재귀 할 필요가있다. 확장 메서드로 사용하면 코드가 좀 더 표현력이 뛰어나지 만, 단지 선호도라는 것을 알게되었습니다.

/// <summary> 
/// Extension method that will recursively search the control's children for a control with the given ID. 
/// </summary> 
/// <param name="parent">The control who's children should be searched</param> 
/// <param name="controlID">The ID of the control to find</param> 
/// <returns></returns> 
public static Control FindControlRecursive(this Control parent, string controlID) 
{ 
    if (!String.IsNullOrEmpty(parent.ClientID) && parent.ClientID.Equals(controlID)) return parent; 

    System.Web.UI.Control control = null; 
    foreach (System.Web.UI.Control c in parent.Controls) 
    { 
     control = c.FindControlRecursive(controlID); 
     if (control != null) 
      break; 
    } 
    return control; 
} 
+0

thanx. 이 작업은 fieldName 매개 변수의 [ClientID]와 [ID]에서 모두 작동합니다. – TroyS

0

이것은 내가 지난 번에 사용했던 확장 방법 :

+0

@ jamar777 thanx, conrol.ID는 전달하지만 control.ClientId는 전달하지 않으면 작동합니다. user_control (즉, 동일한 user_control의 여러 인스턴스) 인스턴스의 자식을 찾으려고하기 때문에 ClientID를 사용해야합니다. – TroyS

+0

컨트롤을 비교할 코드를 업데이트 할 수 없습니다 .ClientID? – jmar777

+0

업데이트 용 코드 – jmar777