skhan //technology enthusiast
ASP.NET, Baking, Cooking, Photoshoping, Webbing & The Rest...

Finding a Nested Data Control

Tuesday, 21 October 2008 09:10 by skhan

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!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5