2011-09-13 22 views

回答

3

您需要通过您的控件递归的:(C#代码)

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) 
    } 
+0

thanx。这适用于fieldName参数中的[ClientID]和[ID]。 – TroyS

0

这是我在过去的时代所使用的扩展方法。我发现使用它作为扩展方法会使代码更具表现力,但这只是一种偏好。

/// <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

@ jamar777 thanx,如果你传递了conrol.ID但是不能用于control.ClientId,因为我试图找到一个user_control的实例(即多个相同的user_control实例)的孩子,我不得不使用ClientID。 – TroyS

+0

难道你不能更新代码,然后比较control.ClientID? – jmar777

+0

只需更新代码示例即可与ClientID进行比较,而不需要使用ID – jmar777