FindControl() method for Dynamically Nested Controls on PostBack
How do you get a specific nested control of dynamically created controls (i开发者_运维问答.e. the child of a dynamic control)? The FindControl() method does not work because it only deals with TopLevel dynamic controls I believe.
You need to recurse through your controls: (C# code)
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)
}
This is an extension method I've used in times past. I've found that using it as an extension method makes the code a little more expressive, but that's just preference.
/// <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;
}
精彩评论