FindControl method doesn't work in some cases. For instance you won't be able to get to a DataList which is nested in another DataList. This "reality" came to my realization when I was trying to do the same today morning. I googled "Finding a datacontrol within a datacontrol"* and I landed at Coding Horror.
The solution lies in using a recursive find control method. Here's the code:
// recursive control finder ! Blisssss!
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;
}
Example:
DataList nestedDataList = this.FindControlRecursive(rootDataList, "nestedDataList") as DataList;
*at times bad search strings work!