Ako získate konkrétnu vnorenú kontrolu naddynamicky vytvorené ovládacie prvky (t. j. dieťa dynamického ovládacieho prvku)? Metóda FindControl () nefunguje, pretože verím, že sa zaoberá iba dynamickými ovládacími prvkami TopLevel.
odpovede:
3 pre odpoveď č. 1Musíte sa vrátiť pomocou ovládacích prvkov: (kód 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 pre odpoveď č. 2
Toto je metóda rozšírenia, ktorú som používal v minulosti. Zistil som, že jej použitie ako metódy rozšírenia robí kód trochu výraznejším, ale to je len preferencia.
/// <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;
}