C#
Hi,
I've been developing c# web applications for a couple of years and there is one issue I keep coming upagainst that I can't find a logical way to solve.
I have a control I wish to access in code behind, this control is deep within the markup; burried within ContentPlaceHolders, UpdatePanels, Panels, GridViews, EmptyDataTemplates, TableCells (or whatever structure you like.. the point is it has more parents than farthers for justice).
How can I use FindControl("")
to access this control without doing this:
Page.Form.Controls[1].Controls[1].Controls[4].Controls[1].Controls[13].Controls[1].Controls[0].Controls[0].Controls[4].FindControl("");
Write a helper method called FindControlRecursive as provided by Jeff Atwood himself.
private Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
Recursive Page.FindControl
Use Recursive FindControl:
public T FindControl<T>(string id) where T : Control
{
return FindControl<T>(Page, id);
}
public static T FindControl<T>(Control startingControl, string id) where T : Control
{
// this is null by default
T found = default(T);
int controlCount = startingControl.Controls.Count;
if (controlCount > 0)
{
for (int i = 0; i < controlCount; i++)
{
Control activeControl = startingControl.Controls[i];
if (activeControl is T)
{
found = startingControl.Controls[i] as T;
if (string.Compare(id, found.ID, true) == 0) break;
else found = null;
}
else
{
found = FindControl<T>(activeControl, id);
if (found != null) break;
}
}
}
return found;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With