Useful Sitecore Extensions for an ASP.NET Repeater Control

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.

[code language=”csharp”]
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
}
}
[/code]

As a basic example, I have the repeater below with an sc:Text Sitecore control in it.

[code language=”html”]
<asp:Repeater ID="_rptr" runat="server" OnItemDataBound="_rptr_ItemDataBound">
<ItemTemplate>
<sc:Text ID="_scText" runat="server" Field="Name" />
</ItemTemplate>
</asp:Repeater>
[/code]

Filling the list:

[code language=”csharp”]
protected void Page_Load(object sender, EventArgs e)
{
_rptr.DataSource = Sitecore.Context.Item.GetChildren().ToList();
_rptr.DataBind();
}
[/code]

When the item is bond to the repeater:

[code language=”csharp”]
protected void _rptr_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.IsItemOrAltItem())
{
e.BindScFieldControl("_scText");
}
}
[/code]

Make sure to include the using statement:

[code language=”csharp”]
using Site.Extensions;
[/code]

If you come up with any other repeater extensions, then please leave them in the comments.

One thought on “Useful Sitecore Extensions for an ASP.NET Repeater Control

Add yours

Leave a Reply

Powered by WordPress.com.

Up ↑

%d bloggers like this: