Asp.net 用于回发时动态嵌套控件的FindControl()方法
如何获取动态创建控件的特定嵌套控件(即动态控件的子控件)?FindControl()方法不起作用,因为我认为它只处理顶级动态控件。您需要通过控件递归:(C代码)Asp.net 用于回发时动态嵌套控件的FindControl()方法,asp.net,vb.net,Asp.net,Vb.net,如何获取动态创建控件的特定嵌套控件(即动态控件的子控件)?FindControl()方法不起作用,因为我认为它只处理顶级动态控件。您需要通过控件递归:(C代码) 这是我过去使用过的一种扩展方法。我发现使用它作为扩展方法会使代码更具表现力,但这只是一种偏好 /// <summary> /// Extension method that will recursively search the control's children for a control with the given
这是我过去使用过的一种扩展方法。我发现使用它作为扩展方法会使代码更具表现力,但这只是一种偏好
/// <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;
}
//
///扩展方法,该方法将递归搜索控件的子控件,以查找具有给定ID的控件。
///
///应搜索控件谁的孩子
///要查找的控件的ID
///
公共静态控件FindControlRecursive(此控件父控件,字符串controlID)
{
如果(!String.IsNullOrEmpty(parent.ClientID)和&parent.ClientID.Equals(controlID))返回父对象;
System.Web.UI.Control=null;
foreach(父控件中的System.Web.UI.Control c)
{
control=c.FindControlRecursive(controlID);
if(控件!=null)
打破
}
返回控制;
}
@jamar777 thanx,如果您传递的是conrol.ID,而不是control.ClientId,则此选项有效。因为我试图找到一个用户\控件实例(即同一个用户\控件的多个实例)的子对象,所以我必须使用ClientID。难道你不能更新代码然后与控件进行比较吗?ClientID?只是更新了代码示例以与ClientID进行比较,而不是ID@jamar777谢谢更新。我试过了,但还是没找到。可能是因为传递的客户端id例如是(ctl03$RemoveButton)。不确定这是否是原因。thanx。这适用于fieldName参数中的[ClientID]和[ID]。
/// <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;
}