Show Parent Fields

Show Parent Fields

Controls featured in this example:

  • Sitecore Web Control

Classes featured in this example:

  • Sitecore.Data.Items.Item
  • Sitecore.StringUtil

Show Parent Fields C# Web Control Code

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

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

string titleField = parent["title"];
string teaserField = Sitecore.Web.UI.WebControls.FieldRenderer.Render(parent, "TeaserImage", "mh=60");
if (string.IsNullOrEmpty(titleField) || string.IsNullOrEmpty(teaserField)) 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);
string displayName = Sitecore.StringUtil.GetString(item.DisplayName, item.Name);
//using : for colon and   for space
output.Write("{0}: {1}", "Item", displayName);
output.RenderEndTag(); //P

output.Write("{0}&#58;&#160;{1}", "Parent Title", "<b>" + titleField + "</b><br/>");
output.Write("{0}&#58;&#160;{1}", "Parent Teaser Image", teaserField);

output.RenderEndTag(); //Div


Show Parent Fields C# Web Control Output

Parent Title: Field Values
Parent Teaser Image:

Notes

This snippet uses an index to reference the item’s field and the parent of the item

  • Accesses the raw value of the field
  • Returns an empty string if the field does not exist or the field value is null
  • Does not generate inline editing controls for the Page Editor
  • Useful for simple field types