If you are like me and you find yourself using ASP.NET Repeater’s all the time, then here are some useful extension methods I use.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Sitecore.Data.Items; using Sitecore.Web.UI.WebControls; namespace Site.Extensions { public static class RepeaterItemEventArgsExtensions { #region Methods public static Item GetItem(this RepeaterItemEventArgs e) { return e.Item.DataItem as Item; } public static void BindScFieldControl(this RepeaterItemEventArgs e, string scControlName, Item i = null, bool useParent = false, string fieldName = "") { if (i == null) { i = e.GetItem(); } if (useParent) { i = i.Parent; } FieldControl t = e.Item.FindControl(scControlName) as FieldControl; if (t != null) { if (!string.IsNullOrEmpty(fieldName)) { t.Field = fieldName; } if (t != null) { t.Item = i; } } } public static void BindTextControl(this RepeaterItemEventArgs e, string controlName, string value) { ITextControl ctrl = e.Item.FindControl(controlName) as ITextControl; if (ctrl != null) { ctrl.Text = value; } } public static void BindControlVisiblity(this RepeaterItemEventArgs e, string controlName, bool visible) { Control ctrl = e.Item.FindControl(controlName) as Control; if (ctrl != null) { ctrl.Visible = visible; } } public static bool IsItemOrAltItem(this RepeaterItemEventArgs e) { return e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem; } #endregion } }
As a basic example, I have the repeater below with an sc:Text Sitecore control in it.
<asp:Repeater ID="_rptr" runat="server" OnItemDataBound="_rptr_ItemDataBound"> <ItemTemplate> <sc:Text ID="_scText" runat="server" Field="Name" /> </ItemTemplate> </asp:Repeater>
Filling the list:
protected void Page_Load(object sender, EventArgs e) { _rptr.DataSource = Sitecore.Context.Item.GetChildren().ToList(); _rptr.DataBind(); }
When the item is bond to the repeater:
protected void _rptr_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.IsItemOrAltItem()) { e.BindScFieldControl("_scText"); } }
Make sure to include the using statement:
using Site.Extensions;
If you come up with any other repeater extensions, then please leave them in the comments.
Image may be NSFW.
Clik here to view.
Clik here to view.
