Reputation: 6549
It has been a while since I have had to do tree traversal and would like some input. Here is a sample tree:
The tree is my ASP.NET page. This page is made from 2 master pages and the content page. What I want to do is find the control that is my 2nd master page's primary content and then place all the controls inside in a flat data structure such as a list.
So given that the Orange node is the 2nd master page's primary ContentPlaceHolder, I would like to store all those in the blue ellipse in my list. I have already created some code to return me all child, grandchild, etc of a control in a collection with this:
private IEnumerable<Control> GetChildControls(Control parentControl)
{
foreach (Control control in parentControl.Controls)
{
yield return control;
foreach(Control grandchild in GetChildControls(control))
{
yield return grandchild;
}
}
}
But I am a bit stuck on how to filter this tree to a node and it's children. If it helps, the orange node should be the following:
<asp:Content ID="SystemMasterMainContentPlaceHolder" runat="server" ContentPlaceHolderID="MainContentPlaceholder">
Upvotes: 4
Views: 433
Reputation: 70552
You could basically use a combination of the method you already have, and a GetChildById()
method.
private Control GetChildById(string controlId, Control parent)
{
return GetChildControls(parent).First(c => c.ID == controlId);
}
This re-uses the tree traversal that is done by GetChildControls
. Note that it will throw an exception if the control is not found - if you don't want that, use FirstOrDefault
instead of First
.
You could potentially use it like so:
GetChildControls(GetChildById("SystemMasterMainContentPlaceHolder", Page));
Upvotes: 2