Get Ancestors

Get Ancestors

Controls featured in this example:

  • Sitecore Web Control

Classes featured in this example:

  • Sitecore.Context
  • Sitecore.Data.Items.Item

Ancestors C# Web Control Code

Sitecore.Data.Items.Item item = Sitecore.Context.Item;
if (item == null) return;

Sitecore.Data.Items.Item[] ancestors = item.Axes.SelectItems("ancestor::*");
if (ancestors == null) return;

output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold; width:100%; clear:both");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
output.Write("C# Web Control Real-time Output");
output.RenderEndTag();

output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-size:x-small; width:100%; clear:both");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.P);
//using : for colon and   for space
output.Write("{0}: {1}", "Item", item.DisplayName);
output.RenderEndTag(); //P
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Ol);

foreach (Sitecore.Data.Items.Item ancestor in ancestors)

    output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Li);
    output.Write("{0}: {1}", "Ancestor", ancestor.DisplayName);
    output.RenderEndTag();
}

output.RenderEndTag(); //Ol 
output.RenderEndTag(); //Div


Ancestors C# Web Control Output

  1. Ancestor: Ancestor Axis
  2. Ancestor: Content Display
  3. Ancestor: Developers
  4. Ancestor: Home
  5. Ancestor: Content
  6. Ancestor: sitecore

Notes

  • This snippet uses a Sitecore query
  • Compare the results with the output from "Document Order"