Validation against Controls outside of the current NamingContainer
I had a situation where I needed to do this recently. I googled of course, and came up with an overloaded FindControl method. I implemented this in my code, and all seemed well. UNTIL… came the time to get the data posted from my control. I had controls nested in a UserControl, and that usercontrol nested within a FormView. When the postback occurred, I was able to retrieve all values from controls directly in the formview but none from within the controls inside my usercontrol. A buddy of mine helped me out on this, and believe me.. it was no fun tracking down. the values “not being posted” was actually a flaw in the FindControl method override. Please use this piece of code in the naming container that your validators reside, if they in fact need to validate against controls outside:
{
Control c = base.FindControl(id, pathOffset);
if (c != null)
return c;
return FindControl(Page, id);
}
public Control FindControl(Control parent, string id)
{
Control recurse;
if (parent.ID == id)
{
return parent;
}
foreach (Control child in parent.Controls)
{
recurse = FindControl(child, id);
if (recurse != null)
{
return recurse;
}
}
return null;
}