Get Parent Item

Get Parent Item

Controls featured in this example:

  • Sitecore Web Control

Classes featured in this example:

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

Parent Item C# Web Control Code

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

Sitecore.Data.Items.Item parent = item.Parent;
if (parent == 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.P);
output.Write("{0}&#58;&#160;{1}", "Parent", "<b>" + parent.DisplayName + "</b>");
output.RenderEndTag(); //P

//alternative to parent.Parent
Sitecore.Data.Items.Item grandparent = item.Parent.Parent;
if(grandparent != null)
{
    output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.P);
    output.Write("{0}&#58;&#160;{1}", "Parent of Parent", "<b>" + grandparent.DisplayName + "</b>");
    output.RenderEndTag(); //P
}
output.RenderEndTag(); //Div


Parent Item C# Web Control Output

Parent: Ancestor Axis

Parent of Parent: Content Display

Notes

  • Sitecore provides specialized classes for templates and media items
  • Please refer to code that invokes these specialized classes if the item to be accessed is a template or a media item